package com.wasu.cs.ui;

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 android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

import com.wasu.cs.model.Model;
import com.wasu.cs.model.SearchModel;
import com.wasu.cs.model.SearchModel.Assets;
import com.wasu.cs.model.SearchModel.AssetsItem;
import com.wasu.cs.protocol.SearchProtocol;
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.statistics.WasuStatistics;
import com.wasu.widgets.focuswidget.CustomFocusGridView;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

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

public class FragmentSearchResult extends Fragment {
	private final String TAG = "FragmentSearchResult";
	
	public final static String KEY_SEARCH_RESULT = "searchResult";
	private CustomFocusGridView.GridViewColumnBeginListener onGridViewColumnBeginListener;

	public CustomFocusGridView getResultFGV() {
		return mResultFGV;
	}

	private CustomFocusGridView mResultFGV;
	private LinearLayout mCatalogWarperLinLay;
	private SearchResultCatalogItem mPreviousCatalogItem = null;
	
	private SearchFGVAdapter mSearchFGVAdapter;
	
	private Assets mAssets;
	
	private CatalogChangeListener mListener;
	
	private ISearchResult iSearchResult;
	
	private List<AssetsItem> mAssetes = new ArrayList<SearchModel.AssetsItem>(); //初始化的 - 保存搜索结果变量(用于规避tag部分时间失效)
	
	@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 {
			iSearchResult = (ISearchResult) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString()
					+ " must implement ISearchResult");
		}
	}

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

		mListener = new CatalogChangeListener() {

			@Override
			public void onCatalogChange(SearchResultCatalogItem v) {
				setCurrentCatalog(v);
				Assets assets = v.returnAssets();
				mAssetes.clear();
				mAssetes.addAll(assets.getAssetsItems());
			}
		};
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_search_result, container, false);
		mResultFGV = (CustomFocusGridView) view.findViewById(R.id.search_result_fgv);
		mResultFGV.setFocusHightlightDrawable(R.drawable.tv_select_focus);
		mResultFGV.postAnimation(200, null);
		mResultFGV.setFocusShadowDrawable(R.drawable.focus_shadow);
		//mResultFGV.setOnScrollListener(new PauseOnScrollListener(ImageFetcherModule.getInstance().getImageLoader(), true, true));
		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;

				/*	if (position < mAssetes.size()) {
						AssetsItem item = mAssetes.get(position);*/
					if (position < mAssets.getAssetsItems().size()) {
						AssetsItem item = mAssets.getAssetsItems().get(position);

						// statistics
						if (position < 100) {
							WasuStatistics.getInstance().BigDatasearchClick(iSearchResult.getSearchKeyword(), item.getId());
						}

						IntentMap.startIntent(
								getActivity(),
								null,
								item.getLayout(),
								item.getJsonUrl(),
								null);
					}else{
						WLog.w(TAG, "onItemClick() 点击项出现越界. 请求项："+position+" 实际长度:"+mAssetes.size());
					}
				} else {
					WLog.w(TAG, "onItemClick() unknow tag: " + tag);
				}
			}
		});
		mResultFGV.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				SearchResultCatalogItem catalogitem= (SearchResultCatalogItem)mCatalogWarperLinLay.findViewById(mResultFGV.getNextFocusUpId());
				Assets itemdata=catalogitem.getData();
				int asset_size=itemdata.getAssetsItems().size();
				if(position>asset_size-10&&asset_size<itemdata.getTotal()){
					requestSearchDataBypage(itemdata.getPage()+1,itemdata);
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		});
		mResultFGV.setNextFocusLeftId(iSearchResult.getNextLeftFocusViewId());
		mResultFGV.setOnGridViewColumnBeginListener(new CustomFocusGridView.GridViewColumnBeginListener() {
			@Override
			public void onColumnBegin() {
				if (null != onGridViewColumnBeginListener) {
					onGridViewColumnBeginListener.onColumnBegin();
				}
			}
		});
		mSearchFGVAdapter = new SearchFGVAdapter();
		mResultFGV.setAdapter(mSearchFGVAdapter);
		mCatalogWarperLinLay = (LinearLayout) view.findViewById(R.id.search_result_catalog_warper_linLay);
		return view;
	}
	private void requestSearchDataBypage(int page,final Assets itemdata) {
		Uri fetchUri = Uri.parse(itemdata.getJsonUrl());
		fetchUri = fetchUri.buildUpon()
				.appendQueryParameter("page", String.valueOf(page))
				.appendQueryParameter("psize", String.valueOf(100))
				.build();
		WLog.i(TAG, "requestSearchDataBypage fetchUri="+fetchUri.toString());
		SearchProtocol protocol = new SearchProtocol();

		protocol.fetch(fetchUri.toString(),
				new ProtocolCallbackBase() {

					@Override
					public void onProtocolCallback(boolean success, String msg, Model model) {
						SearchModel mSearchModel = (SearchModel) model;
						if(mSearchModel != null && mSearchModel.getAssetes()!=null){
							Assets assets=mSearchModel.getAssetes().get(0);
							for(int i=0;i<assets.getAssetsItems().size();i++){
								itemdata.getAssetsItems().add(assets.getAssetsItems().get(i));
							}
							itemdata.setPage(assets.getPage());
							SearchFGVAdapter adapter=((SearchFGVAdapter)(mResultFGV.getAdapter()));
							adapter.notifyDataSetChanged();
						}
					}
				});
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		show();
	}

	/**
	 * show search result
	 */
	private void show() {
		SearchModel model = iSearchResult.getSearchResult();
		if (null == model) {
			WLog.w(TAG, "show() no model found");
			return;
		}
		
		initCatalog(model.getAssetes());
	}
	
	private void initCatalog(List<Assets> assetes) {
		if (null == assetes || assetes.isEmpty()) {
			WLog.w(TAG, "initCatalog() no assetes found");
			return;
		}
		mAssetes.clear();
		int size = assetes.size();

		SearchResultCatalogItem catalogItem = null;
		LinearLayout.LayoutParams params;
		for (int i = 0; i < size; i++) {
			params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

			catalogItem = new SearchResultCatalogItem(getActivity().getBaseContext());
			catalogItem.setLayoutParams(params);
			catalogItem.setId(SearchResultCatalogItem.ID + i);
			// control the first catlog item next focus up

			// control the last catlog item next focus down
			if(i == (size - 1)) {
				catalogItem.setNextFocusRightId(catalogItem.getId());
			}
			catalogItem.setNextFocusDownId(mResultFGV.getId());
			catalogItem.setData(assetes.get(i));
			catalogItem.setCatalogChangeListener(mListener);
			catalogItem.setIndex(i);
			mCatalogWarperLinLay.addView(catalogItem);
			
			
			
			Assets assets =catalogItem.returnAssets();
			mAssetes.addAll(assets.getAssetsItems());
		}
		
		
		setCurrentCatalog((SearchResultCatalogItem) mCatalogWarperLinLay.getChildAt(0));
	}

	private void refreshResult(Assets assets) {
		mAssets = assets;

		mResultFGV.scrollTo(0, 0);
		mResultFGV.reset();
		mResultFGV.setSelection(0);
		mSearchFGVAdapter.setData(mAssets);
		mSearchFGVAdapter.notifyDataSetChanged();
		mSearchFGVAdapter.notifyDataSetInvalidated();
	}

	/**
	 * current catalog item to show
	 * @param view
	 */
	private void setCurrentCatalog(SearchResultCatalogItem view) {
		if (null == view) {
			WLog.w(TAG, "setCurrentCatalog() no view found");
			return;
		}

		Assets assets = view.getData();
		if (null == assets || assets == mAssets) {
			WLog.w(TAG, "setCurrentCatalog() no assets found or it's the same one");
			return;
		}

		if (null != mPreviousCatalogItem) {
			mPreviousCatalogItem.onCatalogSelecte(false);
		}
		view.onCatalogSelecte(true);
		mPreviousCatalogItem = view;
		mResultFGV.setNextFocusUpId(view.getId());

		refreshResult(view.getData());
	}


	@Override
	public void onDetach() {
		super.onDetach();
		try {
		     Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
		     childFragmentManager.setAccessible(true);
		     childFragmentManager.set(this, null);
		     } catch (NoSuchFieldException e) {
		        throw new RuntimeException(e);
		     } catch (IllegalAccessException e) {
		        throw new RuntimeException(e);
		     }
	}

	public void setOnGridViewColumnBeginListener(CustomFocusGridView.GridViewColumnBeginListener lietener) {
		this.onGridViewColumnBeginListener = lietener;
	}

	class SearchFGVAdapter extends BaseAdapter {

		private Assets mAssets;
		private List<AssetsItem> mAssetsItems;
		public void setData(Assets assets) {
			if (null == assets) {
				return;
			}

			this.mAssets = assets;
			mAssetsItems = this.mAssets.getAssetsItems();

		}

		@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;
//			if (null == convertView) {
//				item = new SearchResultItem(getActivity().getBaseContext());
//				convertView = item;
//				convertView.setTag(assetsItem);
//			}
//			item = (SearchResultItem) convertView;
//			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;

			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 search result
	 */
	public static interface ISearchResult {

		/**
		 * get search result
		 * @return SearchModel search result
		 */
		public abstract SearchModel getSearchResult();

		public abstract int getNextLeftFocusViewId();

		public abstract String getSearchKeyword();
	}

}
