package com.kfzs.duanduan;

import android.content.Context;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.download.DownloadTask;
import com.kfzs.android.view.tag.FlowLayout;
import com.kfzs.android.view.tag.TagAdapter;
import com.kfzs.android.view.tag.TagFlowLayout;
import com.kfzs.appstore.utils.restful.KFZSNetwork;
import com.kfzs.duanduan.bean.DownloadStatus;
import com.kfzs.duanduan.utils.InstallButtonUtils;
import com.kfzs.duanduan.bll.UrlBll;
import com.kfzs.duanduan.datashare.KFZSDDContentSession;
import com.kfzs.duanduan.event.EventDownloadHandler;
import com.kfzs.duanduan.proto.ApiResponseOuterClass;
import com.kfzs.duanduan.proto.HotWordsOuterClass;
import com.kfzs.duanduan.proto.MistinessNamesOuterClass;
import com.kfzs.duanduan.utils.net.ResponseNetworkTask;
import com.kfzs.duanduan.utils.dlg.DownBtnUtils;
import com.kfzs.duanduan.utils.dlg.HelperUtils;
import com.kfzs.duanduan.utils.net.APIRequest;
import com.kfzs.duanduan.utils.net.APIRequestInstance;
import com.kfzs.duanduan.adp.AdpSearchGame;
import com.kfzs.duanduan.adp.AdpSearchRecord;
import com.kfzs.duanduan.adp.AdpSearchViewPager;
import com.orhanobut.logger.Logger;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class ActSearch extends BaseCompatActivity {

    private static final String TAG = ActSearch.class.getSimpleName();
    private final String TAG_REQUEST_URL = "ActSearch:TAG_REQUEST_URL";
    private Map<String, InstallButtonUtils> mInstallButtonMgrMap = new HashMap<>();

    @BindView(R.id.edt_act_search_keyword)
    AutoCompleteTextView mEdtKeyWord;
    @BindView(R.id.img_act_search_clear)
    ImageView mImgClear;

    @BindView(R.id.tabs_act_search)
    TabLayout mTabLayout;
    @BindView(R.id.viewpager_act_search)
    ViewPager mViewPager;
    @BindView(R.id.search_history_listview)
    ListView mListRecord;

    @BindView(R.id.layout_activity_search_record)
    View mViewRecord;
    @BindView(R.id.layout_activity_search_content)
    View mViewContent;


    private AdpSearchRecord mAdpSearchRecord;
    private TagAdapter<HotWordsOuterClass.HotWords> hotWordAdapter;
    ;
    private List<HotWordsOuterClass.HotWords> lHotWords = new ArrayList<>();

    private String mStrSearchKey;

    private EventDownloadHandler.OnDownCallback mOnDownCallback;
    private AdpSearchViewPager mAdpSearchViewPager;

    private AdpSearchGame mAdpSearchGame;
    private ArrayAdapter<String> mAdpKeyWords;

    private boolean mIsAutoShowTxt = true;//是否自动提示输入，不然在点搜索历史的时候，也会自动提示

    private boolean isDownLoad = true;//是否显示有下载

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);

        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        Aria.download(this).register();

        mAdpSearchViewPager = new AdpSearchViewPager(this);
        mAdpSearchRecord = new AdpSearchRecord(this, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                setShowKeyTips(false);
                showRecord(false);
                mEdtKeyWord.setText(mAdpSearchRecord.getItem(position).getKey());
                doQueryTask(mAdpSearchRecord.getItem(position).getKey());
            }
        });
        //设置返回主页的按钮
        mTabLayout.setupWithViewPager(mViewPager);


        setSearchInputStatus();
        setInputEvents();
        initTabGame();
        //initTabNewGame();
        //initTabTest();


        loadSearchHistory();
        loadHotTagView();
        mViewPager.setAdapter(mAdpSearchViewPager);
    }

    private void setShowKeyTips(boolean isAutoShowTxt) {
        mIsAutoShowTxt = isAutoShowTxt;
        if (!mIsAutoShowTxt) {
            mAdpKeyWords.clear();
            mAdpKeyWords.notifyDataSetChanged();
        }
    }


    /**
     * 载入搜索历史列表
     */
    private void loadSearchHistory() {
        View tvFooter = LayoutInflater.from(this).inflate(R.layout.listview_item_search_histroy_footer, null);
        mListRecord.addFooterView(tvFooter);
        mListRecord.setAdapter(mAdpSearchRecord);

        tvFooter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mAdpSearchRecord.getCount() < 1) {
                    return;
                }
                mAdpSearchRecord.clear();
                mAdpSearchRecord.notifyDataSetChanged();
            }
        });
    }


    /**
     * 载入热门标签，用得以前别人的，没去具体了解了
     */
    private void loadHotTagView() {

        TagFlowLayout tagList = findViewById(R.id.search_tagflow_layout);
        tagList.setMaxSelectCount(1);
        hotWordAdapter = new TagAdapter<HotWordsOuterClass.HotWords>(lHotWords) {
            @Override
            public View getView(FlowLayout parent, int position, HotWordsOuterClass.HotWords o) {

                TextView tv = (TextView) LayoutInflater.from(ActSearch.this).inflate(R.layout.hot_tag_item, parent, false);
                tv.setText(o.getHotWord());
                return tv;
            }
        };

        tagList.setAdapter(hotWordAdapter);
        tagList.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                setShowKeyTips(false);
                showRecord(true);
                mEdtKeyWord.setText(lHotWords.get(position).getHotWord());
                doQueryTask(lHotWords.get(position).getHotWord());
                return false;
            }
        });

        APIRequest hotWordsRequest = APIRequestInstance.getReqUrl(TAG, UrlBll.AppStoreApi.HOTWORDS, null, new ResponseNetworkTask() {

            @Override
            public void onSuccess(ApiResponseOuterClass.ApiResponse apiResponse) {
                lHotWords.clear();
                lHotWords.addAll(apiResponse.getHotWordsList());
                hotWordAdapter.notifyDataChanged();
            }

            @Override
            public void onFail(int code, String msg) {
                Logger.d("onFail", msg);
            }

        }, HelperUtils.makeErr(getString(R.string.toast_init_tag_fail)));
        KFZSNetwork.addRequest(hotWordsRequest);
    }


    /**
     * 是否显示搜索历史
     *
     * @param isShowRecord
     */
    private void showRecord(boolean isShowRecord) {
        mViewRecord.setVisibility(isShowRecord ? View.VISIBLE : View.GONE);
        mViewContent.setVisibility(isShowRecord ? View.GONE : View.VISIBLE);
    }

    /**
     * 初始化游戏Tab
     */
    private void initTabGame() {
        View view = View.inflate(this, R.layout.list_search, null);
        ListView listView = view.findViewById(R.id.list_list_search);
        listView.setEmptyView(view.findViewById(R.id.download_mgr_empty_view));
        mAdpSearchGame = new AdpSearchGame(this);
        mAdpSearchGame.setmInstallButtonMgrMap(mInstallButtonMgrMap);
        listView.setAdapter(mAdpSearchGame);

        mAdpSearchViewPager.addView(view, R.string.tab_search_game);
    }

    /**
     * 初始化游戏NewGame
     */
    private void initTabNewGame() {
        View view = View.inflate(this, R.layout.list_search, null);
        ListView listView = view.findViewById(R.id.list_list_search);
        listView.setEmptyView(view.findViewById(R.id.download_mgr_empty_view));

        //mAdpSearchNewGame = new AdpSearchNewGame(this);
        //mAdpSearchNewGame.setmInstallButtonMgrMap(mInstallButtonMgrMap);
        //listView.setAdapter(mAdpSearchNewGame);

        mAdpSearchViewPager.addView(view, R.string.tab_search_newgame);
    }

    /**
     * 初始化游戏Test
     */
    private void initTabTest() {
        View view = View.inflate(this, R.layout.list_search, null);
        ListView listView = view.findViewById(R.id.list_list_search);
        listView.setEmptyView(view.findViewById(R.id.download_mgr_empty_view));

        //mAdpSearchTest = new AdpSearchTest(this);
        //mAdpSearchTest.setmInstallButtonMgrMap(mInstallButtonMgrMap);
        //listView.setAdapter(mAdpSearchTest);

        mAdpSearchViewPager.addView(view, R.string.tab_search_test);
    }


    /**
     * 自动转到输入模式
     */
    private void setSearchInputStatus() {
        mEdtKeyWord.setFocusable(true);
        mEdtKeyWord.setFocusableInTouchMode(true);
        mEdtKeyWord.requestFocus();
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(mEdtKeyWord, 0);
    }


    /**
     * 监听输入框，如果是按回车就搜索，有内容时显示清除按钮等。
     */
    private void setInputEvents() {
        mAdpKeyWords = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
        mEdtKeyWord.setAdapter(mAdpKeyWords);
        //以逗号为分隔符
//        mEdtKeyWord.setTokenizer(new AutoCompleteTextView.CommaTokenizer());
        mEdtKeyWord.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mImgClear.setVisibility(TextUtils.isEmpty(s) ? View.GONE : View.VISIBLE);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mIsAutoShowTxt) {
                    loadKeyWords();
                } else {
                    mEdtKeyWord.setSelection(mEdtKeyWord.length());
                }
                setShowKeyTips(true);
                if (s.length() < 1) {
                    showRecord(true);
                    return;
                }
            }
        });

        mEdtKeyWord.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    doQueryTask(mEdtKeyWord.getText().toString());
                }
                return false;
            }
        });
    }

    private void loadKeyWords() {
        if (mEdtKeyWord.length() < 1) {
            return;
        }
        KFZSNetwork.stopByTag(TAG_REQUEST_URL);
        HashMap<String, String> paramsurl = new HashMap<>();
        paramsurl.put("q", mEdtKeyWord.getText().toString().trim());
        APIRequest bannerRequest = APIRequestInstance.getReqUrl(TAG, UrlBll.AppStoreApi.SEARCH_KEYWORDS,
                paramsurl, new ResponseNetworkTask() {
                    @Override
                    public void onSuccess(ApiResponseOuterClass.ApiResponse apiResponse) {
                        List<MistinessNamesOuterClass.MistinessNames> list = apiResponse.getMistinessNamesList();
                        mAdpKeyWords.clear();
                        for (MistinessNamesOuterClass.MistinessNames min : list) {
                            mAdpKeyWords.add(min.getGameNames());
                        }
                        mAdpKeyWords.notifyDataSetChanged();
                        //强制匹配
                        mAdpKeyWords.getFilter().filter(mEdtKeyWord.getText().toString());
                    }

                    @Override
                    public void onFail(int code, String msg) {

                    }
                }, null);
        bannerRequest.setTag(TAG_REQUEST_URL);
        KFZSNetwork.addRequest(bannerRequest);
    }


    /**
     * 主要的点击事件监听
     *
     * @param v
     */
    @OnClick({R.id.ibtn_act_serach, R.id.btn_act_search_search, R.id.img_act_search_clear})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibtn_act_serach:

                try {
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE))
                            .hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                this.finish();
                break;
            case R.id.btn_act_search_search:
                doQueryTask(mEdtKeyWord.getText().toString());
                break;
            case R.id.img_act_search_clear:
                mEdtKeyWord.setText("");
                mImgClear.setVisibility(View.GONE);
                break;
        }
    }


    /**
     * 提交搜索请求
     *
     * @param keyword
     */
    private void doQueryTask(String keyword) {
        if (keyword == null || keyword.trim().length() < 1) {
            return;
        }
        mStrSearchKey = keyword.trim();
        mAdpSearchRecord.add(mStrSearchKey);

        HashMap<String, String> params = new HashMap<>();
        if (null != KFZSDDContentSession.getInstance().findOutHeadSession(app)) {
            params.put(UrlBll.HeadParams.AUTHORIZATION,
                    KFZSDDContentSession.getInstance().findOutHeadSession(app).getToken());
        }
        UMConfigUtils.onEvent(UMConfigUtils.Event.GAME_SEARCH);
        HashMap<String, String> paramsurl = new HashMap<>();
        paramsurl.put("q", mStrSearchKey);
        APIRequest bannerRequest = APIRequestInstance.getReqUrlWithHead(TAG, UrlBll.AppStoreApi.SEARCH,
                params, paramsurl, new ResponseNetworkTask() {
                    @Override
                    public void onSuccess(ApiResponseOuterClass.ApiResponse apiResponse) {
                        mAdpSearchGame.clear();
                        //mAdpSearchNewGame.clear();
                        //mAdpSearchTest.clear();
                        mAdpSearchGame.addAll(apiResponse.getGamesList());
                        //mAdpSearchNewGame.addAll(apiResponse.getOpenServersList());
                        //mAdpSearchTest.addAll(apiResponse.getOpenTestsList());

                        mAdpSearchGame.notifyDataSetChanged();
                        //mAdpSearchNewGame.notifyDataSetChanged();
                        //mAdpSearchTest.notifyDataSetChanged();
                        showRecord(false);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        Logger.d(TAG, "搜索结果获取失败" + msg);
                    }
                }, HelperUtils.makeErr(getString(R.string.toast_init_data_fail)));
        KFZSNetwork.addRequest(bannerRequest);
        MobclickAgent.onEvent(SheepApp.mContext, UMConfigUtils.Event.GAME_SEARCH.getKey());
    }

    /**
     * 格式化搜索结果显示
     *
     * @param strKey
     * @param strCount
     * @return
     */
    private Spanned getHTMLStr(String strKey, String strCount) {
        return Html.fromHtml("与<font color='#fa6324' size='20'>“" + strKey + "”</font>" + "结果相关" +
                "共 <font color='#fa6324' size='25'>" + strCount + "</font>" + " 条");
    }


    /**
     * 下载任务状态的事件
     *
     * @param info
     */
    @Subscribe
    public void onEventMainThread(DownloadStatus info) {
        if (mOnDownCallback == null) {
            mOnDownCallback = DownBtnUtils.installBtnStatus(mInstallButtonMgrMap);
        }

        EventDownloadHandler
                .newInstance(this, mOnDownCallback)
                .setmTag(TAG)
                .handlDownloadResult(info);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Download.onTaskStop void stopDownload(DownloadTask task){
        if(!isDownLoad){
            mAdpSearchGame.notifyDataSetChanged();
        }
    }
    @Download.onTaskStart void startDownload(DownloadTask task){
        if(!isDownLoad){
            mAdpSearchGame.notifyDataSetChanged();
        }
    }

    @Download.onTaskComplete void completeDownload(DownloadTask task){
        if(!isDownLoad){
            mAdpSearchGame.notifyDataSetChanged();
        }
    }

    @Download.onTaskRunning void runDownload(DownloadTask task){
        if(!isDownLoad){
            mAdpSearchGame.notifyDataSetChanged();
        }
    }
}
