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.model.entity.SearchAppRecord;
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 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;
import butterknife.OnClick;

/**
 * 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() {
        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){
                    title_search_input.setText(item.getInput());
                    title_search_input.setSelection(item.getInput().length());
                }
            }
        });
        title_search_input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    title_search_commit.performClick();
                }
                return false;
            }
        });
        title_search_input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                title_search_input.removeCallbacks(autoSearchRunnable);
                if(editable.toString().isEmpty() && !searchRecordList.isEmpty()){//输入框内容为空且有搜索记录时显示搜索记录
                    search_app_list.setVisibility(View.VISIBLE);
                    frame_container.setVisibility(View.INVISIBLE);
                } else {
                    title_search_input.postDelayed(autoSearchRunnable, 1000L);//1秒后自动搜索
                }
            }
        });
    }

    private Runnable autoSearchRunnable = new Runnable() {
        @Override
        public void run() {
            title_search_commit.performClick();
        }
    };
    private Comparator<SearchAppRecord> comparator = new Comparator<SearchAppRecord>() {
        @Override
        public int compare(SearchAppRecord item1, SearchAppRecord item2) {
            return item2.getCount() - item1.getCount();
        }
    };
    @Override
    public void initData() {
        //初始化搜索历史
        List<SearchAppRecord> newSgrList = MyDbManager.getInstance().getAllSearchAppRecord();
        ListUtil.addAll(allSearchRecordList, newSgrList);
        Collections.sort(allSearchRecordList, comparator);
        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);
        }
    }

    @OnClick({R.id.title_search_commit, R.id.title_img_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_search_commit:
                toSearchApp();
                break;
            case R.id.title_img_back:
                finish();
                break;
        }
    }

    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 = title_search_input.getText().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);
    }
}
