package com.wasu.cs.ui;

import java.util.List;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;

import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;

import com.wasu.cs.model.FilterModel;
import com.wasu.cs.model.Model;
import com.wasu.cs.model.SearchModel.AssetsItem;
import com.wasu.cs.protocol.FilterProtocol;
import com.wasu.cs.protocol.SearchProtocol.ProtocolCallbackBase;
import com.wasu.cs.widget.SearchResultCatalogItem;
import com.wasu.cs.widget.SearchResultItem;
import com.wasu.frescoimagefetchermodule.PauseOnScrollListener;
import com.wasu.module.log.WLog;
import com.wasu.widgets.focuswidget.CustomFocusGridView;

public class FragmentFilterResult extends Fragment {
	private final String TAG = "FragmentFilterResult";

	private CustomFocusGridView mResultFGV;

	private IFilterResult iFilterResult;

	private FilterResultAdapter mFilterResultAdapter;
	private CustomFocusGridView.GridViewColumnBeginListener mGridViewColumnBeginListener
			;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// This makes sure that the container activity has implemented
		// the ISearchResult interface. If not, it throws an exception.
		try {
			iFilterResult = (IFilterResult) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement ISearchResult");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_filter_result, container, false);
		
		mResultFGV = (CustomFocusGridView) view.findViewById(R.id.filter_result_fgv);
		mResultFGV.setFocusHightlightDrawable(R.drawable.tv_select_focus);
		mResultFGV.postAnimation(200, null);
		mResultFGV.setFocusShadowDrawable(R.drawable.focus_shadow);
		mResultFGV.setOnScrollListener(new PauseOnScrollListener(true,true));
		mResultFGV.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Object tag = view.getTag();
				if (tag instanceof AssetsItem) {
					AssetsItem item = (AssetsItem) tag;

					IntentMap.startIntent(
							getActivity(),
							null,
							item.getLayout(),
							item.getJsonUrl(),
							null);
				} else {
					WLog.w(TAG, "onItemClick() unknow tag: " + tag);
				}			
			}
		});
		mResultFGV.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				WLog.i(TAG, "position="+position);
				int asset_size=iFilterResult.getFilterResult().size();
				if(position>asset_size-10&&asset_size<iFilterResult.getFilterMode().getAssetes().get(0).getTotal()){
					requestFilterDataBypage(iFilterResult.getFilterMode().getPage()+1);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		});
		//给GridView添加向左的回调监听
		mResultFGV.setOnGridViewColumnBeginListener(new CustomFocusGridView.GridViewColumnBeginListener() {
			@Override
			public void onColumnBegin() {
				if (null != mGridViewColumnBeginListener) {
					mGridViewColumnBeginListener.onColumnBegin();
				}
			}
		});
		mFilterResultAdapter = new FilterResultAdapter();
		mResultFGV.setAdapter(mFilterResultAdapter);

		return view;
	}
	private void requestFilterDataBypage(int page) {
		String url = Uri.parse(iFilterResult.getFilterMode().getJsonUrl()).buildUpon()
				.appendQueryParameter("page", String.valueOf(page))
				.appendQueryParameter("psize", String.valueOf(100))
				.build()
				.toString();
		WLog.i(TAG, "requestFilterDataBypage url="+url);
		new FilterProtocol().fetch(url, new ProtocolCallbackBase() {
			
			@Override
			public void onProtocolCallback(boolean success, String msg, Model model) {
				FilterModel mFilterModel = (FilterModel) model;
				WLog.i(TAG, "mFilterModel="+mFilterModel.getJSON().toString());
				if(mFilterModel!=null&&mFilterModel.getAssetes()!=null){
					iFilterResult.getFilterMode().getFilterAsset().getAssetsItems().addAll(mFilterModel.getFilterAsset().getAssetsItems());
					iFilterResult.getFilterMode().setPage(mFilterModel.getPage());
					//iFilterResult.getFilterMode().setJsonUrl(mFilterModel.getJsonUrl());
					mFilterResultAdapter.setData(iFilterResult.getFilterMode().getFilterAsset().getAssetsItems());
					mFilterResultAdapter.notifyDataSetChanged();
				}
			}
		});
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		show();
	}

	/**
	 * show search result
	 */
	private void show() {
		List<AssetsItem> filterResult = iFilterResult.getFilterResult();
		if (null == filterResult || filterResult.isEmpty()) {
			WLog.w(TAG, "show() no filterResult found");
			return;
		}

		refreshResult(filterResult);
	}

	private void refreshResult(List<AssetsItem> assetsItems) {
		mResultFGV.reset();

		mFilterResultAdapter.setData(assetsItems);
		mFilterResultAdapter.notifyDataSetChanged();
	}

	public void setOnGridViewColumnBeginListener(CustomFocusGridView.GridViewColumnBeginListener listener) {
		this.mGridViewColumnBeginListener = listener;
	}

	class FilterResultAdapter extends BaseAdapter {

		private List<AssetsItem> mAssetsItems;
		public void setData(List<AssetsItem> assetsItems) {
			mAssetsItems = assetsItems;
		}

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

		@Override
		public Object getItem(int position) {
			return null == mAssetsItems ? null : mAssetsItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			AssetsItem assetsItem = (AssetsItem) getItem(position);

			SearchResultItem item = new SearchResultItem(getActivity().getBaseContext());
			item.setTag(assetsItem);
			AbsListView.LayoutParams params = new AbsListView.LayoutParams(getResources().getDimensionPixelOffset(R.dimen.d_183dp), getResources().getDimensionPixelOffset(R.dimen.d_241dp));
			item.setLayoutParams(params);
			item.show(assetsItem);
			return item;
		}
	}

	/**
	 * interface for catalog change
	 */
	public static interface CatalogChangeListener {
		/**
		 * callback when catalog change
		 * @param v the previous catalog item
		 */
		public abstract void onCatalogChange(SearchResultCatalogItem v);
	}

	/**
	 * interface for get filter result
	 */
	public static interface IFilterResult {

		/**
		 * get the result we need
		 * @return List<AssetsItem> filter result
		 */
		public abstract List<AssetsItem> getFilterResult();
		public abstract FilterModel getFilterMode();
	}

}
