package com.wasu.cs.ui;

import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.wasu.cs.adapter.ChannelHomeAdapter;
import com.wasu.cs.model.CatData;
import com.wasu.cs.model.CatData.BaseElement;
import com.wasu.cs.widget.BlockLinearLayout;
import com.wasu.cs.widget.FocusGridViewEx;
import com.wasu.module.log.WLog;

import java.util.ArrayList;
import java.util.List;

import cn.com.wasu.main.R;

/**
 * 4.0二级列表页整体的fragment，包含Header和Container两部分
 * Created by LiuYang on 6/23/15.
 */
public class FragmentBlockChannel extends FragmentChannelBase {

    private BlockLinearLayout mBlockFrameLayout;
    private FragmentBlockHeader mBlockHeader;
    private FragmentBlockContainer mBlockContainer;
    private ChannelHomeAdapter mAdapter;

    private boolean mInit = false;

    private final BlockLinearLayout.OnFocusSearchListener mOnFocusSearchListener =
            new BlockLinearLayout.OnFocusSearchListener() {
                @Override
                public View onFocusSearch(View focused, int direction) {
                    // if headers is running transition,  focus stays
                    View res = mBlockHeader.focusSearch(focused,direction);
                    if(res != null) {
                        return res;
                    }
                    else if(direction == View.FOCUS_DOWN){
                    	/**由于这里没有返回return res，造成了从tabItem跳转焦点到推荐位的时候焦点错位，导致焦点无法左右**/
                    	 //mBlockContainer.getView().requestFocus();
                    	if(null != mBlockContainer){
                    		res = mBlockContainer.focusSearch(focused, direction);
                    	}
                    }

                    return res;
                }
            };

    private final BlockLinearLayout.OnChildFocusListener mOnChildFocusListener =
            new BlockLinearLayout.OnChildFocusListener() {

                @Override
                public boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {

                    if (getChildFragmentManager().isDestroyed() || mBlockHeader.getView() == null) {
                        return true;
                    }

                    if (mBlockHeader.getView().requestFocus(direction, previouslyFocusedRect)) {
                        return true;
                    }

                    if (mBlockContainer.getView().requestFocus(direction, previouslyFocusedRect)) {
                        return true;
                    }
                    return mBlockHeader.getView().requestFocus(direction, previouslyFocusedRect);
                }

                @Override
                public void onRequestChildFocus(View child, View focused) {
                    if (getChildFragmentManager().isDestroyed()) {
                        return;
                    }
                }
            };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        
        View rootView = inflater.inflate(R.layout.fragment_block, container, false);
        mBlockFrameLayout = (BlockLinearLayout) rootView.findViewById(R.id.blockFrame);
        mBlockFrameLayout.setOnFocusSearchListener(mOnFocusSearchListener);
        mBlockFrameLayout.setOnChildFocusListener(mOnChildFocusListener);

        mBlockHeader = (FragmentBlockHeader) getChildFragmentManager()
                .findFragmentById(R.id.headerBlock);
        mBlockContainer = (FragmentBlockContainer) getChildFragmentManager()
                .findFragmentById(R.id.containerBlock);

        mAdapter = new ChannelHomeAdapter(getChildFragmentManager());
        mAdapter.setOnGridClumnListener(new FocusGridViewEx.FocusGridViewColumnListener() {
            @Override
            public void onColumnBegin() {
                mBlockContainer.requestPreView();
            }

            @Override
            public void onColumnEnd() {
                mBlockContainer.requestNextView();
            }
        });
        if(!mInit) {
            mBlockHeader.setViewPager(mBlockContainer.getViewPager());
            mBlockHeader.setTabAdapter(mAdapter);
            mBlockContainer.setAdapter(mAdapter);
            mInit = true;
        }
        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        addToBackPressed();
    }

    @Override
    protected boolean onBackPressed() {
        if(mBlockContainer.getView().hasFocus()) {
            mBlockContainer.onBackPressed();
            getHandler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mBlockHeader.onBackPressed();
                }
            },400);
            return true;
        }
        return false;
    }
    
    @Override
    public void onDestroyView() {
    	super.onDestroyView();
    	cleanResource();
    }
    
    public void cleanResource(){
    	if(mBlockFrameLayout != null){
    		mBlockFrameLayout.removeAllViews();
    		mBlockFrameLayout = null;
    	}
    	if(mBlockHeader != null){
    		mBlockHeader.cleanResource();
    		mBlockHeader = null;
    	}
    	if(mBlockContainer != null){
    		mBlockContainer.cleanResource();
    		mBlockContainer = null;
    	}
    	
    	/**退出时清除数据**/
    	if(mAdapter != null){
    		mAdapter.clearData();
    		mAdapter = null;
    	}
    	
    }
    
    public void initData(CatData catData) {
    	mBlockHeader.setCatProp(catData.getCat().getCatProp());
        List<BaseElement> cats = new ArrayList<BaseElement>();
        int size = catData.getChildCats().size();
        for (int i = 0; i < size; i++) {
            BaseElement element = catData.getChildCats().get(i);
            if (element.getSelected() != 0) {
                WLog.d("danxx", "tab selected position:" + i);
                Log.i("FragmentBlockChannel", "Msg:initData==");
                mAdapter.setTabSelected(i);
            }
            if (element.getLayout().equalsIgnoreCase("Wasu_Search")) {
                mBlockHeader.setSearchElement(element);
            } else if (element.getLayout().equalsIgnoreCase("Wasu_Filter")) {
                mBlockHeader.setFilterElement(element);
            } else {
                cats.add(element);
            }
        }

        mBlockHeader.saveData(catData);
        mBlockFrameLayout.requestFocus();
        mAdapter.setData(cats);
        mAdapter.notifyDataSetChanged();
    }
}