package com.wasu.cs.ui;

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

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

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

import com.wasu.cs.model.RecommendModel;
import com.wasu.cs.model.RecommendModel.Recommend;
import com.wasu.cs.widget.HeaderGridViewEx;
import com.wasu.cs.widget.PosterItemLayout;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.frescoimagefetchermodule.PauseOnScrollListener;
import com.wasu.module.log.WLog;
import com.wasu.widget.HeaderGridView.FixedViewInfo;

public class FragmentSearchRecommend extends Fragment {
	private final String TAG = "FragmentSearchRecommend";
	
	public static final String KEY_RECOMMEND = "recommend";
	public static final String KEY_HOT_RECOMMEND = "hotRecommend";

	private HeaderGridViewEx mHeaderGV;
	private TextView noteTextView;
	private ISearchRecommend iSearchRecommend;
	private HeaderGridViewEx.GridViewColumnBeginListener onGridViewColumnBeginListener;

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

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

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_search_recommend, container, false);
		noteTextView=(TextView)view.findViewById(R.id.search_no_result_hint_tv);
		mHeaderGV = (HeaderGridViewEx) view.findViewById(R.id.search_recommend_headerGV);
		mHeaderGV.setFocusHightlightDrawable(R.drawable.tv_select_focus);
		mHeaderGV.setFocusShadowDrawable(R.drawable.focus_shadow);
		mHeaderGV.postAnimation(200, null);
		mHeaderGV.setNumColumns(4);
		mHeaderGV.setDefaultColumnNumber(4);
		mHeaderGV.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Object tag = view.getTag();
				if (tag instanceof Recommend) {
					Recommend recommend = (Recommend) tag;
					IntentMap.startIntent(getActivity(), null, recommend.getLayout(), recommend.getJsonUrl(), null);
				} else {
					WLog.w(TAG," onItemClick() unknow tag: " + tag);
				}
			}
		});
		//mHeaderGV.setOnScrollListener(new PauseOnScrollListener(ImageFetcherModule.getInstance().getImageLoader(), true, true));
		mHeaderGV.setOnScrollListener(new PauseOnScrollListener(true,true));
		mHeaderGV.setOnGridViewColumnBeginListener(new HeaderGridViewEx.GridViewColumnBeginListener() {
			@Override
			public void onColumnBegin() {
				if (null != onGridViewColumnBeginListener) {
					onGridViewColumnBeginListener.onColumnBegin();
				}
			}
		});
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		RecommendModel model = iSearchRecommend.getRecommend();
		WLog.i(TAG, "model="+model);
		if (null != model) {
			noteTextView.setVisibility(View.GONE);
			mHeaderGV.setVisibility(View.VISIBLE);
			show(model);
		} else {
			WLog.w(TAG," onStart() no model found");
			mHeaderGV.setVisibility(View.GONE);
			noteTextView.setVisibility(View.VISIBLE);
			
		}
	}

	public HeaderGridViewEx getHeaderGV() {
		return mHeaderGV;
	}
	/**
	 * 恢复时让其滚动到顶端
	 */
	@Override
	public void onResume() {
		super.onResume();
		mHeaderGV.scrollTo(0, 0);
		mHeaderGV.reset();
		mHeaderGV.setSelection(0);
	}

	/**
	 * show recommend view
	 * @param model recommend data
	 */
	private void show(RecommendModel model) {
		TextView hotTV = new TextView(getActivity().getBaseContext());
		hotTV.setLayoutParams(new LayoutParams(getResources().getDimensionPixelOffset(R.dimen.d_200dp), LayoutParams.WRAP_CONTENT));
		hotTV.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelOffset(R.dimen.s_26sp));
		hotTV.setText(R.string.search_recommend_hot);
		FixedViewInfo headerView = new FixedViewInfo();
		headerView.isSelectable = false;
		headerView.view = hotTV;
		mHeaderGV.addHeaderView(1, headerView);
		
		List<Recommend> hotRecommends = model.getHotRecommends();
		if (hotRecommends != null && !hotRecommends.isEmpty()) {
			int size = hotRecommends.size();
			FixedViewInfo[] infoList = new FixedViewInfo[size];
			for (int i = 0; i < size; i++) {
				View item = LayoutInflater.from(getActivity().getBaseContext()).inflate(R.layout.item_search_recommend_header, null);
	
				final TextView tv = (TextView) item.findViewById(R.id.search_recommend_header_tv);
				tv.setText(hotRecommends.get(i).getTitle());
				final ImageView image = (ImageView) item.findViewById(R.id.search_recommend_header_imgv);
				FrescoImageFetcherModule.getInstance().attachImage(hotRecommends.get(i).getPicUrl(), image);

				infoList[i] = new FixedViewInfo();
				infoList[i].isSelectable 	= true;
				infoList[i].view			= item;
				infoList[i].data			= hotRecommends.get(i);
			}

			mHeaderGV.addHeaderView(4, infoList);
		}

		TextView watchTV = new TextView(getActivity().getBaseContext());
		watchTV.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		watchTV.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.s_26sp));
		watchTV.setText(R.string.search_recommend_watch);
		FixedViewInfo watch = new FixedViewInfo();
		watch.isSelectable = false;
		watch.view = watchTV;
		mHeaderGV.addHeaderView(1, watch);

		RecommendAdapter adapter = new RecommendAdapter();
		adapter.setData(model.getWatchRecommends());
		mHeaderGV.setAdapter(adapter);
	}

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

	class RecommendAdapter extends BaseAdapter {

		private List<Recommend> mRecommends;
		public void setData(List<Recommend> recommends) {
			mRecommends = recommends;
		}
		
		@Override
		public int getCount() {
			return null == mRecommends ? 0 : mRecommends.size();
		}

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

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

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			PosterItemLayout layout = null;
			if (null == convertView) {
				layout = new PosterItemLayout(getActivity().getBaseContext());
				convertView = layout;
			}
			
			Recommend recommend = (Recommend) getItem(position);
			layout = (PosterItemLayout) convertView;
			LayoutParams params = new LayoutParams(getResources().getDimensionPixelOffset(R.dimen.d_183dp), getResources().getDimensionPixelOffset(R.dimen.d_241dp));
			layout.setLayoutParams(params);
			layout.setImageUrl(recommend.getPicUrl());
			layout.setName(recommend.getTitle());
			
			layout.setTag(recommend);

			return layout;
		}
	}
	
	public static interface ISearchRecommend {
		public abstract RecommendModel getRecommend();
	}

	@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);
		     }
	}
	
}
