package com.sheep.gamegroup.view.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.AppCompatAutoCompleteTextView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.absBase.IHomePageSearch;
import com.sheep.gamegroup.model.entity.SearchAppRecord;
import com.sheep.gamegroup.util.ApiUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.MyDbManager;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.ArrayAdapter;
import com.sheep.gamegroup.view.fragment.FgtSearchApp;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by realicing on 2018/9/13.
 * realicing@sina.com
 */
public class ActSearchApp extends BaseActivity {
    //    @BindView(R.id.title_search_input)
//    AppCompatAutoCompleteTextView title_search_input;
    @BindView(R.id.search_app_list)
    ListView search_app_list;
    @BindView(R.id.frame_container)
    View frame_container;
//    @BindView(R.id.title_search_commit)
//    TextView title_search_commit;

    @Override
    protected int getLayoutId() {
        return R.layout.act_search_app;
    }

    private FgtSearchApp fgtSearchApp;

    @Override
    public void initView() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Bundle bundle = new Bundle();
        Fragment fragment = getSupportFragmentManager().findFragmentByTag("tag");
        if (fragment == null) {
            fragment = new FgtSearchApp();
            fragment.setArguments(bundle);
            transaction.add(R.id.frame_container, fragment, "tag");
            transaction.commitAllowingStateLoss();
        } else {
            fragment.setArguments(bundle);
            transaction.replace(R.id.frame_container, fragment);
            transaction.commitAllowingStateLoss();
        }
        if (fgtSearchApp == null && fragment instanceof FgtSearchApp)
            fgtSearchApp = (FgtSearchApp) fragment;
        inputAdapter = new ArrayAdapter<SearchAppRecord>(SheepApp.getInstance(), R.layout.item_serach_record, searchRecordList) {
            @Override
            public boolean convert(int position, View view, ViewGroup parent, final SearchAppRecord item) {
                TextView item_search_record_name = (TextView) view.findViewById(R.id.item_search_record_name);
                ImageView item_search_record_x = (ImageView) view.findViewById(R.id.item_search_record_x);
                ViewUtil.setText(item_search_record_name, item.getInput());
                item_search_record_x.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        searchRecordMap.remove(item.getInput());
                        allSearchRecordList.remove(item);
                        searchRecordList.clear();
                        ListUtil.addAll(searchRecordList, allSearchRecordList, 10);
                        inputAdapter.notifyDataSetChanged();
                        MyDbManager.getInstance().hideSearchApp(item);
                        if (searchRecordList.isEmpty()) {
                            frame_container.setVisibility(View.VISIBLE);
                            search_app_list.setVisibility(View.INVISIBLE);
                        }
                    }
                });
                return true;
            }
        };
        search_app_list.setAdapter(inputAdapter);
    }

    private ArrayAdapter<SearchAppRecord> inputAdapter;

    @Override
    public void initListener() {
        TitleBarUtils.getInstance()
                .setShowOrHide(this, true)
                .setTitleFinish(this)
                .setSearchBox(this, "搜索任务名称/游戏名称",
                        (v, actionId, event) -> {
                            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                                toSearchApp();
                            }
                            return false;
                        },
                        (text) -> {
                            if (text.isEmpty() && !searchRecordList.isEmpty()) {//输入框内容为空且有搜索记录时显示搜索记录
                                search_app_list.setVisibility(View.VISIBLE);
                                frame_container.setVisibility(View.INVISIBLE);
                            } else {
                                frame_container.postDelayed(() -> toSearchApp(), 1000L);//1秒后自动搜索
                            }
                        })
                .setRightBtn(this, "搜索", 0,
                        v -> toSearchApp())
                .setShowOrHide(this, true);
        search_app_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                SearchAppRecord item = ListUtil.getItem(searchRecordList, position);
                if (item != null) {
                    TitleBarUtils.getInstance().setSearchText(ActSearchApp.this, item.getInput());
                    if (item instanceof IHomePageSearch)
                        ApiUtil.postTopSearchStatisticsClickTopSearch((IHomePageSearch) item);
                }
            }
        });
    }

    @Override
    public void initData() {
        //初始化搜索历史
        List<SearchAppRecord> newSgrList = MyDbManager.getInstance().getAllSearchAppRecord();
        ListUtil.addAll(allSearchRecordList, newSgrList);
        Collections.sort(allSearchRecordList, (item1,item2) -> item2.getCount() - item1.getCount());
        ListUtil.addAll(searchRecordList, allSearchRecordList, 10);
        for (SearchAppRecord item : allSearchRecordList) {
            searchRecordMap.put(item.getInput(), item);
        }
        inputAdapter.notifyDataSetChanged();
        if (searchRecordList.isEmpty()) {
            frame_container.setVisibility(View.VISIBLE);
            search_app_list.setVisibility(View.INVISIBLE);
        } else {
            frame_container.setVisibility(View.INVISIBLE);
            search_app_list.setVisibility(View.VISIBLE);
        }
    }

    List<SearchAppRecord> searchRecordList = new ArrayList<>();
    List<SearchAppRecord> allSearchRecordList = new ArrayList<>();
    Map<String, SearchAppRecord> searchRecordMap = new HashMap<>();

    //尝试搜索游戏
    private void toSearchApp() {
        search_app_list.setVisibility(View.INVISIBLE);
        frame_container.setVisibility(View.VISIBLE);
        String inputText = TitleBarUtils.getInstance().getSearchText(this).toString();
        if (!TextUtils.isEmpty(inputText)) {
            //保存搜索到数据库
            SearchAppRecord searchRecord = searchRecordMap.get(inputText);
            if (searchRecord == null) {
                searchRecord = new SearchAppRecord();
                searchRecord.setInput(inputText);
                searchRecordList.add(searchRecord);
                allSearchRecordList.add(searchRecord);
                searchRecordMap.put(inputText, searchRecord);
            }
            searchRecord.setTime(System.currentTimeMillis());
            searchRecord.addCount();
            MyDbManager.getInstance().saveOrUpdate(searchRecord);
            inputAdapter.notifyDataSetChanged();
        }
        fgtSearchApp.toSearch(inputText);
    }
}
