package com.gh.gamecenter;

import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.gh.base.BaseFragmentActivity;
import com.gh.common.constant.Config;
import com.gh.common.util.DataUtils;
import com.gh.common.util.DisplayUtils;
import com.gh.gamecenter.db.SearchHistoryDao;
import com.gh.gamecenter.eventbus.EBSearch;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.SystemBarTintManager;
import com.gh.gamecenter.manager.SystemBarTintManager.SystemBarConfig;
import com.gh.gamecenter.search.SearchGameDetailFragment;
import com.gh.gamecenter.search.SearchGameListFragment;
import com.gh.gamecenter.search.SearchHistoryFragment;

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


public class SearchActivity extends BaseFragmentActivity {

	private SearchGameDetailFragment game_detail_fragment;
	private SearchGameListFragment game_list_fragment;
	private SearchHistoryFragment search_history_fragment;

	private RelativeLayout searchBack;
	private EditText searchInput;
	private ImageView searchCancel;
	private TextView searchButton;

	private SearchHistoryDao dao;

	private String searchKey;

	private int currentTab;

	private boolean isSearchDetail;

	private Handler handler =  new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == 1){
				setResultPresentModel(1);
			}
		}
	};

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("currentTab", currentTab);
		outState.putString("searchKey", searchKey);
	}

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

		View contentView = View.inflate(this, R.layout.activity_search, null);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			setTheme(R.style.AppTheme);
			setTranslucentStatus(true);
			SystemBarTintManager tintManager = new SystemBarTintManager(this);
			tintManager.setStatusBarTintEnabled(true);
			tintManager.setStatusBarTintResource(R.color.theme);
			SystemBarConfig config = tintManager.getConfig();
			contentView.setPadding(0, config.getPixelInsetTop(false), 0,
					config.getPixelInsetBottom());
		}
		setContentView(contentView);

		dao = new SearchHistoryDao(this);

		boolean isFromHome = getIntent().getBooleanExtra("clicked", false);
		String hint = getIntent().getStringExtra("hint");

		setActionBarLayout(hint, isFromHome);

		if (savedInstanceState != null) {
			currentTab = savedInstanceState.getInt("currentTab", 0);
			searchKey = savedInstanceState.getString("searchKey", null);
			if (TextUtils.isEmpty(searchKey)) {
				currentTab = 0;
			} else {
				isSearchDetail = true;
				searchInput.setText(searchKey);
				searchInput.setSelection(searchInput.getText().length());
			}
		} else {
			currentTab = 0;
			if (isFromHome && !TextUtils.isEmpty(hint)) {
				searchKey = hint;
				currentTab = 2;
			}
		}

		setResultPresentModel(currentTab);
	}

	public void setActionBarLayout(final String hint, final boolean isFromHome) {
		int actionbar_height = getSharedPreferences(Config.PREFERENCE,
				Context.MODE_PRIVATE).getInt("actionbar_height",
				DisplayUtils.dip2px(getApplicationContext(), 48));

		LinearLayout reuse_actionbar = (LinearLayout) findViewById(R.id.search_actionbar);
		LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, actionbar_height);
		reuse_actionbar.setLayoutParams(lparams);

		searchInput = (EditText) findViewById(R.id.etSearch);
		searchInput.setOnEditorActionListener(new OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
					String newSearchKey = searchInput.getText().toString().trim();
					if (newSearchKey.length() < 1) {
						if (!TextUtils.isEmpty(hint)) {
							newSearchKey = searchInput.getHint().toString();
							isSearchDetail = true;
							searchInput.setText(hint);
							searchInput.setSelection(searchInput.getText().length());
						}
					}
					if (!newSearchKey.equals(searchKey) || currentTab != 2) {
						searchKey = newSearchKey;
						if (!TextUtils.isEmpty(searchKey)) {
							setResultPresentModel(2);
							dao.add(searchKey);
						} else {
							toast("请输入搜索内容");
						}
					}
				}
				return false;
			}
		});
		searchButton = (TextView) findViewById(R.id.btnSearch);
		searchCancel = (ImageView) findViewById(R.id.ivDeleteText);
		searchBack = (RelativeLayout) findViewById(R.id.btnGoBack);

		if (isFromHome && !TextUtils.isEmpty(hint)) {
			isSearchDetail = true;
			searchInput.setText(hint);
			searchInput.setSelection(searchInput.getText().length());
		} else if (!TextUtils.isEmpty(hint)) {
			searchInput.setHint(hint);
		} else {
			searchInput.setHint("搜索游戏...");
		}

		searchButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
				String newSearchKey = searchInput.getText().toString().trim();
				if (newSearchKey.length() < 1) {
					if (!TextUtils.isEmpty(hint)) {
						newSearchKey = searchInput.getHint().toString();
						isSearchDetail = true;
						searchInput.setText(hint);
						searchInput.setSelection(searchInput.getText().length());
					}
				}
				if (!newSearchKey.equals(searchKey) || currentTab != 2) {
					searchKey = newSearchKey;
					if (!TextUtils.isEmpty(searchKey)) {
						setResultPresentModel(2);
						dao.add(searchKey);
						isSearchDetail = false;
					} else {
						toast("请输入搜索内容");
					}
				}
			}
		});

		searchCancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				searchCancel.setVisibility(View.GONE);
				searchInput.setText("");
			}

		});

		searchInput.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) {
				if (s.length() > 0) {
					searchCancel.setVisibility(View.VISIBLE);
				} else {
					searchCancel.setVisibility(View.GONE);
				}
			}

			@Override
			public void afterTextChanged(Editable s) {
				String newSearchKey = s.toString().trim();
				if (!newSearchKey.equals(searchKey)) {
					handler.removeMessages(1);
					searchKey = newSearchKey;
					if (searchKey.length() < 1) {
						setResultPresentModel(0);
					} else if (!isSearchDetail){
						handler.sendEmptyMessageDelayed(1, 300);
					}
				}
			}
		});

		searchBack.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

	}

	private void setResultPresentModel(int model) {
		FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
		hideFragments(transaction);
		switch (model) {
			case 0:
				if (search_history_fragment == null) {
					List<Fragment> list = getSupportFragmentManager().getFragments();
					if (list != null) {
						for (Fragment fragment : list) {
							if (fragment.getClass().equals(SearchHistoryFragment.class)) {
								transaction.remove(fragment);
								break;
							}
						}
					}
				} else {
					transaction.remove(search_history_fragment);
				}
				search_history_fragment = new SearchHistoryFragment();
				transaction.add(R.id.search_result, search_history_fragment);
				currentTab = 0;
				break;
			case 1:
				if (game_list_fragment == null) {
					List<Fragment> list = getSupportFragmentManager().getFragments();
					if (list != null) {
						for (Fragment fragment : list) {
							if (fragment.getClass().equals(SearchGameListFragment.class)) {
								transaction.remove(fragment);
								break;
							}
						}
					}
				} else {
					transaction.remove(game_list_fragment);
				}
				game_list_fragment = new SearchGameListFragment();
				game_list_fragment.setKey(searchKey);
				transaction.add(R.id.search_result, game_list_fragment);
				currentTab = 1;
				break;
			case 2:
				DataUtils.onEvent(SearchActivity.this, "搜索页面", searchKey);

				Map<String, Object> map = new HashMap<>();
				map.put("key", searchKey);
				map.put("from", "搜索页面");
				DataCollectionManager.onEvent(this, "search", map);

				if (game_detail_fragment == null) {
					List<Fragment> list = getSupportFragmentManager().getFragments();
					if (list != null) {
						for (Fragment fragment : list) {
							if (fragment.getClass().equals(SearchGameDetailFragment.class)) {
								transaction.remove(fragment);
								break;
							}
						}
					}
				} else {
					transaction.remove(game_detail_fragment);
				}
				game_detail_fragment = new SearchGameDetailFragment();
				game_detail_fragment.setKey(searchKey);
				transaction.add(R.id.search_result, game_detail_fragment);
				currentTab = 2;
				break;
			default:
				break;
		}
		transaction.commit();
	}

	private void hideFragments(FragmentTransaction transaction) {
		if (game_detail_fragment != null) {
			transaction.hide(game_detail_fragment);
		}
		if (game_list_fragment != null) {
			transaction.hide(game_list_fragment);
		}
		if (search_history_fragment != null) {
			transaction.hide(search_history_fragment);
		}
		List<Fragment> list = getSupportFragmentManager().getFragments();
		if (list != null) {
			for (Fragment fragment : list) {
				transaction.hide(fragment);
			}
		}
	}

	public void onEvent(EBSearch search) {
		isSearchDetail = true;
		String str = search.getKey();
		searchInput.setText(str);
		searchInput.setFocusable(true);
		searchInput.requestFocus();
		searchInput.setSelection(str.length());
		if (search.isSearch()) {
			searchButton.performClick();
		}
	}

	@Override
	public void finish() {
		super.finish();
		DataUtils.onEvent(this, "搜索页面", searchKey);

		Map<String, Object> map = new HashMap<>();
		map.put("key", searchKey);
		map.put("from", "搜索页面");
		DataCollectionManager.onEvent(this, "search", map);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		game_detail_fragment = null;
		game_list_fragment = null;
		search_history_fragment = null;
		searchBack = null;
		searchInput = null;
		searchCancel = null;
		searchButton = null;
		dao = null;
		searchKey = null;
	}
}
