package com.wasu.cs.ui;

import java.lang.ref.WeakReference;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import cn.com.wasu.main.IntentConstant;
import cn.com.wasu.main.R;

import com.wasu.cs.model.FilterConditionModel;
import com.wasu.cs.model.FilterConditionModel.ChildFilter;
import com.wasu.cs.model.FilterConditionModel.Filter;
import com.wasu.cs.model.FilterModel;
import com.wasu.cs.model.Model;
import com.wasu.cs.model.RecommendModel;
import com.wasu.cs.model.SearchModel.AssetsItem;
import com.wasu.cs.protocol.FilterConditionProtocol;
import com.wasu.cs.protocol.FilterProtocol;
import com.wasu.cs.protocol.RecommendProtocol;
import com.wasu.cs.protocol.SearchProtocol.ProtocolCallbackBase;
import com.wasu.cs.ui.FragmentFilterResult.IFilterResult;
import com.wasu.cs.ui.FragmentSearchRecommend.ISearchRecommend;
import com.wasu.cs.widget.wheelview.AbstractWheelAdapter;
import com.wasu.cs.widget.wheelview.OnWheelItemSelectedListener;
import com.wasu.cs.widget.wheelview.WheelView;
import com.wasu.module.log.WLog;
import com.wasu.widgets.focuswidget.CustomFocusGridView;
import com.wasu.statistics.WasuStatistics;

public class ActivityFilter extends ActivityBase implements
		OnWheelItemSelectedListener, ISearchRecommend, IFilterResult {
	private final String TAG = "ActivityFilter";
	private final String PAGEVIEWTYPE = "ActivityFilter";
	private final String PAGENAME = "筛选页";
	private final String CATNAME = "筛选页";

	private final int REQUEST_DELAY_TIME_MS = 500;

	private LinearLayout mWheelViewWrapper;
	
	private FragmentSearchNoResult mNotResultFrag;
	private String mFilterConditionUrl, mFilterUrl, mOldFilterCondiftion = "";

	private FilterHandler mHandler;

	private RecommendModel mRecommendModel;

	private Map<WheelView, String> mFilters = new HashMap<WheelView, String>();
	private List<AssetsItem> mFilterRsults;

	@Override
	protected void doCreate(Bundle savedInstanceState) {
		WLog.i(TAG,"doCreate()");

		setContentView(R.layout.activity_filter);

		mHandler = new FilterHandler(this);

		getDataFromIntent(getIntent());

		setupViews();

		requestFilterCondition();
	}

	@Override
	protected void onResume() {
		WasuStatistics.getInstance().pageViewStart(PAGEVIEWTYPE);
		super.onResume();
	}

	@Override
	protected void onPause() {
		WasuStatistics.getInstance().pageViewEnd(PAGEVIEWTYPE,CATNAME,PAGENAME);
		super.onPause();
	}

	private boolean getDataFromIntent(Intent intent) {
		mFilterConditionUrl = intent.getStringExtra(IntentConstant.DATAURI.value());

		if (TextUtils.isEmpty(mFilterConditionUrl)) {
			return false;
		}
		return true;
	}

	private void setupViews() {
		mWheelViewWrapper = (LinearLayout) findViewById(R.id.filter_wheel_view_wrap);
	}

	private void requestFilterCondition() {
		if (TextUtils.isEmpty(mFilterConditionUrl)) {
			WLog.w(TAG, "requestFilterCondition() mFilterConditionUrl is empty");
			return;
		}
		WLog.i(TAG, "mFilterConditionUrl="+mFilterConditionUrl);
		showLoading();

		new FilterConditionProtocol().fetch(
				mFilterConditionUrl,
				new ProtocolCallbackBase() {

					@Override
					public void onProtocolCallback(boolean success, String msg, Model model) {
						hideLoading();
						if (success) {
							showFilter(model);
						} else {
							// what to do ?!
						}
					}
		});
	}

	private void RequestFilterDataDelay() {
		if (mFilters.isEmpty()) {
			WLog.w(TAG, "prepareToRequestFilterData() map is empty");
			return;
		}

		mHandler.removeMessages(FilterHandler.MSG_REQUEST_FILTER_DELAY);
		mHandler.sendEmptyMessageDelayed(FilterHandler.MSG_REQUEST_FILTER_DELAY, REQUEST_DELAY_TIME_MS);
	}

	private void requestDataByFilters() {
		if (mFilters.isEmpty()) {
			WLog.w(TAG, "requestDataByFilters() map is empty");
			return;
		}

		String filters = "";
		
		Collection<String> values = mFilters.values();
		Iterator<String> it = values.iterator();
		while (it.hasNext()) {
			filters += (String) it.next() + "|";
		}
		filters=filters.substring(0, filters.length()-1);
		if (TextUtils.isEmpty(filters)) {
			WLog.w(TAG, "requestDataByFilters() not filters");
			return;
		}

		if (mOldFilterCondiftion.equals(filters)) {
			WLog.w(TAG, "requestDataByFilters() same filters");
			return;
		}

		// remember the filters, in case of repeated request
		mOldFilterCondiftion = filters;

		showLoading();

		String url = Uri.parse(mFilterUrl).buildUpon()
				.appendQueryParameter("fvalues", filters)
				.appendQueryParameter("page", String.valueOf(1))
				.appendQueryParameter("psize", String.valueOf(100))
				.build()
				.toString();
		WLog.i(TAG, "filters url="+url);
		new FilterProtocol().fetch(url, new ProtocolCallbackBase() {
			
			@Override
			public void onProtocolCallback(boolean success, String msg, Model model) {
				hideLoading();
				if (success) {
					//规避服务器返回的json接口，中文参数没有encode的问题
					((FilterModel)model).setJsonUrl(Uri.parse(mFilterUrl).buildUpon()
					.appendQueryParameter("fvalues", mOldFilterCondiftion).build().toString());
					showResultFrag(model);
				} else {
					showNotResultFrag();
				}
			}
		});
	}

	private void requestRecommendData(String url) {
		if (TextUtils.isEmpty(url)) {
			WLog.w(TAG, "requestRecommendData() url is empty");
			return;
		}

		RecommendProtocol protocol = new RecommendProtocol();
		protocol.fetch(url,
				new ProtocolCallbackBase() {

					@Override
					public void onProtocolCallback(boolean success, String msg, Model model) {
						mRecommendModel = (RecommendModel) model;
						if (null != mRecommendModel
								&& null != mNotResultFrag
								&& mNotResultFrag.isVisible()) {
							mNotResultFrag.show();
						}
					}
				});
	}
	FilterConditionModel filterConditionModel;
	public final int FILTER_MAXNUM=4;
	private void showFilter(Model model) {
		filterConditionModel = (FilterConditionModel) model;

		mFilterUrl = filterConditionModel.getUrl();

		List<Filter> filters = filterConditionModel.getFilters();
		if (null == filters || filters.isEmpty() || TextUtils.isEmpty(mFilterUrl)) {
			Log.w(TAG, " showFilter() filters is empty or mFilterUrl is empty");
			return;
		}
		WLog.i(TAG, "mFilterUrl="+mFilterUrl);
		requestRecommendData(filterConditionModel.getRecommendUrl());

		WheelView wheelView;
		LayoutParams params;
		WVAdapter adapter;
		
		int size = filters.size();
		int len=size>FILTER_MAXNUM?FILTER_MAXNUM:size;
		// 最多4种筛选
		for (int i = 0; i < len; i++) {
			adapter = new WVAdapter();
			adapter.setData(filters.get(i).getChildFilters());

			params = new LayoutParams(0, LayoutParams.MATCH_PARENT);
			params.weight = 1;

			wheelView = new WheelView(getBaseContext());
			wheelView.setFocusable(true);
			wheelView.setFocusableInTouchMode(true);
			wheelView.setLayoutParams(params);
			wheelView.addItemSelectedListener(this);
			wheelView.setAdapter(adapter);
			wheelView.setTag(i);
			mWheelViewWrapper.addView(wheelView);
		}

		if (mWheelViewWrapper.getChildCount() > 0) {
			mWheelViewWrapper.getChildAt(0).requestFocus();
		}
	}
	FilterModel filterModel;
	private void showResultFrag(Model model) {
		if(isFinishing()){
			return;
		}
		if (!(model instanceof FilterModel)) {
			WLog.w(TAG, "showResult() unknow model: " + model);
			showNotResultFrag();
			return;
		}

		filterModel = ((FilterModel) model);
		mFilterRsults = filterModel.getFilterAsset().getAssetsItems();
		if (null == mFilterRsults || mFilterRsults.isEmpty()) {
			WLog.w(TAG, "showResult() mFilterRsults is empty");
			showNotResultFrag();
			return;
		}

		FragmentFilterResult resultFrag = new FragmentFilterResult();
		resultFrag.setOnGridViewColumnBeginListener(new CustomFocusGridView.GridViewColumnBeginListener() {
			@Override
			public void onColumnBegin() {

				if (mWheelViewWrapper.getChildCount() > 0) {
					mWheelViewWrapper.getChildAt(mWheelViewWrapper.getChildCount() - 1).requestFocus();
				}
			}
		});
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.filter_frag_wrapper_fraLay, resultFrag)
//			.addToBackStack(null)
				.commitAllowingStateLoss();
	}

	private void showNotResultFrag() {
		if(isFinishing()){
			return;
		}
		if (null == mNotResultFrag) {
			mNotResultFrag = new FragmentSearchNoResult();
			mNotResultFrag.setOnGridViewColumnBeginListener(new CustomFocusGridView.GridViewColumnBeginListener() {
				@Override
				public void onColumnBegin() {
					if (mWheelViewWrapper.getChildCount() > 0) {
						mWheelViewWrapper.getChildAt(mWheelViewWrapper.getChildCount() - 1).requestFocus();
					}
				}
			});
		}
		getSupportFragmentManager().beginTransaction()
				.replace(R.id.filter_frag_wrapper_fraLay, mNotResultFrag)
//			.addToBackStack(null)
				.commitAllowingStateLoss();
	}

	class WVAdapter extends AbstractWheelAdapter {

		private List<ChildFilter> mData;

		public void setData(List<ChildFilter> data) {
			mData = data;
		}

		@Override
		public int getCount() {
			return null == mData ? 0 : mData.size();
		}

		@Override
		public View getView(int index, View convertView, ViewGroup parent) {
			
			TextView tv = new TextView(getBaseContext());
			tv.setLayoutParams(new LinearLayout.LayoutParams(
					LayoutParams.MATCH_PARENT, getResources()
							.getDimensionPixelOffset(R.dimen.d_50dp)));
			tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources()
					.getDimensionPixelSize(R.dimen.s_24sp));
			// set this will lead text didn't show, don;t why yeah
			// tv.setSingleLine();
			tv.setEllipsize(TruncateAt.MARQUEE);
			tv.setMaxLines(1);
			tv.setGravity(Gravity.CENTER);
			tv.setTextColor(Color.GRAY);
			tv.setText(mData.get(index).getName());

			return tv;
		}
	}

	@Override
	public void onItemSelected(WheelView wheel, View oldV, View selectedV) {
		if (null != oldV) {
			((TextView) oldV).setTextColor(Color.GRAY);
			((TextView) oldV).setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelOffset(R.dimen.s_24sp));
		}
		
		if (null != selectedV) {
			if (wheel.hasFocus()) {
				((TextView) selectedV).setTextColor(Color.YELLOW);
				((TextView) selectedV).setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelOffset(R.dimen.s_36sp));
			} else {
				((TextView) selectedV).setTextColor(Color.WHITE);
				((TextView) selectedV).setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelOffset(R.dimen.s_24sp));
			}

			String selectFilterText = ((TextView) selectedV).getText().toString();
			int i=(Integer)wheel.getTag();
			String selectFilterText2 = filterConditionModel.getFilters().get(i).getValueByName(selectFilterText);
			mFilters.put(wheel, selectFilterText2);
			
			/** 用于自动化测试 **/
			wheel.setContentDescription(selectFilterText);
			
			RequestFilterDataDelay();
		}
	}

	@Override
	public RecommendModel getRecommend() {
		return mRecommendModel;
	}

	@Override
	public List<AssetsItem> getFilterResult() {
		return mFilterRsults;
	}
	@Override
	public FilterModel getFilterMode() {
		// TODO Auto-generated method stub
		return filterModel;
	}
	static class FilterHandler extends Handler {
		public static final int MSG_REQUEST_FILTER_DELAY = 0x7621;

		WeakReference<ActivityFilter> mRef;

		public FilterHandler(ActivityFilter activity) {
			mRef = new WeakReference<ActivityFilter>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			ActivityFilter activity = mRef.get();
			if (null == activity) {
				return;
			}

			switch (msg.what) {
			case MSG_REQUEST_FILTER_DELAY:
				activity.requestDataByFilters();
				break;

			default:
				break;
			}
		}
	}

}
