package com.wasu.cs.ui;

import java.lang.reflect.Field;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import cn.com.wasu.main.R;

import com.wasu.cs.model.RecommendModel;
import com.wasu.cs.ui.FragmentSearchRecommend.ISearchRecommend;
import com.wasu.cs.widget.SearchNotResultRecommendLayout;
import com.wasu.module.log.WLog;
import com.wasu.widgets.focuswidget.CustomFocusGridView;

public class FragmentSearchNoResult extends Fragment {
	private final String TAG = "FragmentSearchNoResult";
	private CustomFocusGridView.GridViewColumnBeginListener mGridViewColumnBeginListener;

	public SearchNotResultRecommendLayout getRecommendLayout() {
		return mRecommendLayout;
	}

	private SearchNotResultRecommendLayout mRecommendLayout;

	private ISearchRecommend iSearchRecommend;
	
	@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_no_result, container, false);
		mRecommendLayout = (SearchNotResultRecommendLayout) view.findViewById(R.id.search_no_result_recommend);

		mRecommendLayout.getFgv().setOnGridViewColumnBeginListener(new CustomFocusGridView.GridViewColumnBeginListener() {
			@Override
			public void onColumnBegin() {
				if (mGridViewColumnBeginListener != null) {
					mGridViewColumnBeginListener.onColumnBegin();
				}
			}
		});
		return view;
	}

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

		show();
	}

	public void show() {
		RecommendModel model = iSearchRecommend.getRecommend();
		if (null != model) {
			mRecommendLayout.setVisibility(View.VISIBLE);
			mRecommendLayout.show(model.getWatchRecommends());
		} else {
			mRecommendLayout.setVisibility(View.GONE);
			WLog.w(TAG, " onStart() no model found");
		}
	}
	@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 listener) {
		this.mGridViewColumnBeginListener = listener;
	}
}
