package com.uiui.zyappstore.activity;

import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.uiui.zyappstore.R;
import com.uiui.zyappstore.adapter.AppAdapter;
import com.uiui.zyappstore.base.BaseActivity;
import com.uiui.zyappstore.bean.AppInfo;
import com.uiui.zyappstore.bean.BaseResponse;
import com.uiui.zyappstore.network.NetInterfaceManager;
import com.uiui.zyappstore.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.schedulers.Schedulers;


public class SearcherActivity extends BaseActivity {
    private static final String TAG = SearcherActivity.class.getSimpleName();

    @BindView(R.id.iv_back)
    ImageView iv_back;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.edit_search)
    EditText edit_search;
    @BindView(R.id.tv_search)
    TextView tv_search;

//    @BindView(R.id.search)
//    SearchView search;

    private AppAdapter mAppAdapter;

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_searcher;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
//        int id = search.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
//        TextView textView = search.findViewById(androidx.appcompat.R.id.search_src_text);
//        textView.setTextColor(Color.BLACK);
//        textView.setHintTextColor(Color.GRAY);//提示字体颜色**

        edit_search.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
        edit_search.setInputType(EditorInfo.TYPE_CLASS_TEXT);
    }

    @Override
    protected void initData() {
        mAppAdapter = new AppAdapter(SearcherActivity.this);
        mAppAdapter.setHasStableIds(true);
        mAppAdapter.setLineShow(false);
        recyclerView.setAdapter(mAppAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
    }

    @Override
    protected void setListener() {
//        search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//            @Override
//            public boolean onQueryTextSubmit(String query) {
//                LogUtils.e("icon_serach", query);
////                OKGO.searchAppbyName(handler, query);
//                return false;
//            }
//
//            @Override
//            public boolean onQueryTextChange(String newText) {
//                madapter.setData(new ArrayList<AppInfo>());
//                madapter.notifyDataSetChanged();
//                return false;
//            }
//        });
        edit_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    switch (event.getAction()) {
                        case KeyEvent.ACTION_UP:
                            //do it
                            if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                                //do something;
                                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                                        .hideSoftInputFromWindow(SearcherActivity.this.getCurrentFocus()
                                                .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                                String text = edit_search.getText().toString();
                                checkContent(text);
                            }
                            return true;
                        default:
                            return true;
                    }
                }
                return false;
            }
        });
        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String text = edit_search.getText().toString();
                checkContent(text);
            }
        });
    }

    private void checkContent(String text) {
        if (TextUtils.isEmpty(text)) {
            getAllAppPackageName();
        } else {
            int setting_admin_app = Settings.System.getInt(getContentResolver(), "setting_admin_app", 1);
            if (setting_admin_app == 0) {
                ToastUtil.debugShow("搜索功能已禁用");
            } else {
                searcheApp(text);
            }
        }
    }

    private void searcheApp(String text) {
        NetInterfaceManager.getInstance()
                .getSearchAdminAppControl()
                .getAdminApp(text)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseResponse<List<AppInfo>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e("searcheApp", "onSubscribe: ");
                    }

                    @Override
                    public void onNext(BaseResponse<List<AppInfo>> listBaseResponse) {
                        Log.e("searcheApp", "onNext: " + listBaseResponse);
                        if (listBaseResponse.code == 200) {
                            List<AppInfo> appInfos = listBaseResponse.data;
                            if (appInfos != null && appInfos.size() > 0) {
                                mAppAdapter.setData(listBaseResponse.data);
                            }
                        } else {
                            mAppAdapter.setData(new ArrayList<>());
                            ToastUtil.show("没有搜索到相关应用");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("searcheApp", "onError: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        Log.e("searcheApp", "onComplete: ");
                    }
                });
    }

    private void getAllAppPackageName() {
        NetInterfaceManager.getInstance()
                .getQueryAllAppObservable()
                .subscribe(new Observer<BaseResponse<List<AppInfo>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e(TAG, "onSubscribe: ");
                    }

                    @Override
                    public void onNext(BaseResponse<List<AppInfo>> listBaseResponse) {
                        if (listBaseResponse.code == 200) {
                            List<AppInfo> appInfos = listBaseResponse.data;
                            if (appInfos != null && appInfos.size() > 0) {
                                mAppAdapter.setData(listBaseResponse.data);
                            }
                        } else {
                            mAppAdapter.setData(new ArrayList<>());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void finish(View view) {
        finish();
    }

}
