package com.mjsheng.myappstore.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;

import com.blankj.utilcode.util.LogUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.mjsheng.myappstore.R;
import com.mjsheng.myappstore.adapter.SearchHistoryAdapter;
import com.mjsheng.myappstore.base.BaseActivity;
import com.mjsheng.myappstore.bean.AppData;
import com.mjsheng.myappstore.bean.AppDateInfo;
import com.mjsheng.myappstore.bean.JsonCallback;
import com.mjsheng.myappstore.bean.LzyResponse;
import com.mjsheng.myappstore.bean.SearchBean;
import com.mjsheng.myappstore.comm.CommonDatas;
import com.mjsheng.myappstore.utils.Configure;
import com.mjsheng.myappstore.utils.MySQLData;
import com.mjsheng.myappstore.utils.Utils;
import com.mjsheng.myappstore.widget.Sound;

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

import okhttp3.Call;
import okhttp3.Response;
import okhttp3.internal.Util;

public class SearchActivity extends BaseActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
    private EditText mSearchEditText;
    private ListView mListView;
    private SearchHistoryAdapter adapter;

    private Sound sound;
    private Handler mHandler = new Handler() {

        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            switch (msg.what) {
                case Configure.SUCCESS:
                    if (data != null) {
                        String httTag = data.getString("httpTag");
                        if (TextUtils.isEmpty(httTag)) {
                            Utils.showToast(SearchActivity.this,"没有搜索到相关内容！");
                            return;
                        }
                        if (null == msg.obj)
                            return;
                        if (httTag.equals(Configure.HTTP_TAG_SEARCH)) {
                            ArrayList<AppDateInfo> serachList = (ArrayList<AppDateInfo>) msg.obj;
                            if (serachList != null && !serachList.isEmpty()) {
                                showSearchResultPageActivity(serachList);
                            } else {
                                Utils.showToast(SearchActivity.this,"没有搜索到相关内容！");
                            }
                        }
                    }
                    break;
            }
        }

    };

    private void showSearchResultPageActivity(ArrayList<AppDateInfo> serachList) {
        LogUtils.e(serachList);
        Intent intent = new Intent(SearchActivity.this, SubjectMoreActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("AppDateInfo", serachList);
        bundle.putString("title", "search_result");
        intent.putExtras(bundle);
        intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        startActivity(intent);
        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_search);
        sound = new Sound(this);

        initView();
    }

    private void initView() {

        mSearchEditText = (EditText) findViewById(R.id.search_edit);
        findViewById(R.id.search_btn).setOnClickListener(this);
        mListView = (ListView) findViewById(R.id.search_ListView);
        adapter = new SearchHistoryAdapter(this);
        mListView.setOnItemClickListener(this);
        mListView.setAdapter(adapter);
        findViewById(R.id.iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        initData();
    }


    private void initData() {
        adapter.histories = AppData.getSearchData(this);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View v) {
        sound.playSoundEffect();
        switch (v.getId()) {
            case R.id.search_btn:
                Utils.CloseKeyBoard(this);
                doSearch();
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String value = (String) adapter.getItem(position);
        mSearchEditText.setText(value);
        doSearch();
    }

    private void doSearch() {
        if (mSearchEditText != null
                && !TextUtils.isEmpty(mSearchEditText.getText())) {

            doPost(mSearchEditText.getText().toString());
            for (int i = 0; i < adapter.histories.size(); i++){
                SearchBean info = adapter.histories.get(i);
                if (info.getCategory().equals(mSearchEditText.getText().toString())){
                    adapter. histories.remove(info);
                }
            }
            SearchBean bean = new SearchBean();
            bean.setCategory(mSearchEditText.getText().toString());
            bean.setSearch_time((int) System.currentTimeMillis());
            AppData.upSearchData(this, mSearchEditText.getText().toString(), (int) System.currentTimeMillis());
            adapter.histories.add(0,bean);
            adapter.notifyDataSetChanged();
        }
    }

    public void doPost(String keyWord) {

        OkGo.post(Configure.HTTP_TAG_SEARCH_URL)
                .tag(this)
                .params("sn", Utils.getSerial())
                .params("key", Configure.HTTP_KEY)
                .params("page", "1")
                .params("keywords", keyWord)
                .cacheKey(Configure.HTTP_TAG_SEARCH_URL)
                .cacheMode(CacheMode.NO_CACHE)
                .execute(new JsonCallback<LzyResponse<List<AppDateInfo>>>() {
                    @Override
                    public void onSuccess(LzyResponse<List<AppDateInfo>> listLzyResponse, Call call, Response response) {
                        Message msg = new Message();
                        msg.what = Configure.SUCCESS;
                        Bundle bundle = new Bundle();
                        bundle.putString("httpTag", Configure.HTTP_TAG_SEARCH);
                        msg.obj = listLzyResponse.data;
                        msg.setData(bundle);
                        mHandler.sendMessage(msg);
                    }
                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        if (response.code() != 200){
                            Utils.showToast(SearchActivity.this, "网络连接不稳定，请稍后重试！");
                        }
                    }

                });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (Utils.isShouldHideInput(v, ev)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
    }
}
