package com.wasu.cs.ui;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;

import com.wasu.cs.model.CatData;
import com.wasu.cs.model.CatData.BaseElement;
import com.wasu.cs.module.WasuCacheModule;
import com.wasu.cs.protocol.CatProtocol;
import com.wasu.cs.widget.ChannelMovieItem;
import com.wasu.cs.widget.IViewItem;
import com.wasu.cs.widget.ViewItemFactory;
import com.wasu.widget.FocusLinearLayout;

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

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

/**
 * Created by LiuYang on 7/10/15.
 */
public class FragmentBlockRecommend extends FragmentChannelBase {

    private ImageView mFirstAd;
    private ImageView mSecondAd;
    private FocusLinearLayout mFirstRecommend;
    private FocusLinearLayout mSecondRecommend;
    private ViewWrapper mTopViewWrapper;
    /**当header部分隐藏快速切换viewpager到首页的一瞬间，推荐位还没有初始化完成，无法获得焦点，flagFocusView用来暂存焦点，不至于焦点丢失**/
    private View flagFocusView;
    
    private int ANIM_DURATION = 500;
    private boolean mIsAnim = false;
    private int mMarginValue = 0;
    
    private boolean mFirstRecommendVisible = true;
    private boolean mSecondRecommendVisible = true;

    private CatData mCatData;
    public boolean mIsNews = false;
    private boolean isFinishInit = false;
    private boolean assetGridViewItemEmpty = true;

    List<BaseElement> mSecondElements = new ArrayList<BaseElement>();

    private FocusLinearLayout.OnChildViewSelectedListener mChildListener = new FocusLinearLayout.OnChildViewSelectedListener() {
        @Override
        public void OnChildViewSelected(View view, boolean b) {
            if(b) {
//                ChannelMovieItem item = (ChannelMovieItem) view;
//                setBgImage(item.getData().getPicUrl());
            }
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater,container,savedInstanceState);
        View  rootView = inflater.inflate(R.layout.fragment_block_recommend,null);
        
        flagFocusView = rootView.findViewById(R.id.flagFocusView);
        
        mFirstAd = (ImageView) rootView.findViewById(R.id.firstAd);
        mSecondAd = (ImageView) rootView.findViewById(R.id.secondAd);

        mFirstRecommend = (FocusLinearLayout) rootView.findViewById(R.id.firstRecommend);
        mFirstRecommend.setFocusHighlightDrawable(R.drawable.tv_select_focus);
        mFirstRecommend.setFocusRealId(R.id.ivPic);
        mFirstRecommend.setFocusMovingDuration(200);
        mFirstRecommend.setOnChildViewSelectedListener(mChildListener);

        mSecondRecommend = (FocusLinearLayout) rootView.findViewById(R.id.secondRecommend);
        mSecondRecommend.setFocusHighlightDrawable(R.drawable.tv_select_focus);
        mSecondRecommend.setFocusRealId(R.id.ivPic);
        mSecondRecommend.setFocusMovingDuration(200);
        mSecondRecommend.setOnChildViewSelectedListener(mChildListener);
        
        mTopViewWrapper = new ViewWrapper(rootView);
        
        return rootView;
    }

    @Override
    protected boolean onBackPressed() {
        if(!mFirstRecommendVisible) {
        	showSecondRecommend();
            showFirstRecommend();
        }
        return false;
    }

    public void initData(CatData catData,String layout) {
    	isFinishInit = false;
        this.mCatData = catData;
        if(layout.equalsIgnoreCase(LayoutCodeMap.RECOMMEND_NEWS)) {
            mIsNews = true;
        }

        List<CatData.Element> elements = catData.getElements();
        for(int i = 0;i < elements.size();i++) {
            String url = elements.get(i).getJsonUrl();
            if(i == 0) {
                initFirstRecommendData(url);
            }
            else if(i == 1) {
                initSecondRecommendData(url);
            }
        }
    }

    private void initFirstRecommendData(String url) {
        mFirstRecommend.removeAllViews();
        final String mUrl = url + "&page=1&psize=20";

        final WasuCacheModule wasuCacheModule = WasuCacheModule.getInstance();
        CatData mCatData = (CatData) wasuCacheModule.getAsObject(mUrl);

        if (mCatData != null) {
            updateFirstRecommendData(mCatData);
            CatProtocol.fetchData(getHandler(), mUrl, new CatProtocol.CatFetchCallback() {
                @Override
                public void onResult(boolean successed, CatData catData) {
                    if (getActivity() == null) {
                        return;
                    }
                    if(catData != null){
                        wasuCacheModule.remove(mUrl);
                        wasuCacheModule.put(mUrl ,catData);
                    }
                }
            });
        }else{
            CatProtocol.fetchData(getHandler(), mUrl, new CatProtocol.CatFetchCallback() {
                @Override
                public void onResult(boolean successed, CatData catData) {
                    if (getActivity() == null) {
                        return;
                    }
                    if(catData != null){
                        updateFirstRecommendData(catData);
                        wasuCacheModule.remove(mUrl);
                        wasuCacheModule.put(mUrl ,catData);
                    }
                }
            });
        }

    }


    /**
     * 组织第一排的推荐数据
     * @param catData
     */
    private void updateFirstRecommendData(CatData catData){
        /***新闻和非新闻的返回的推荐数据格式不一样，所以改为分开处理*/
        int size = 0;
        if(catData != null){
            if (mIsNews) {
                size = catData.getElements().size();
            } else {
                size = catData.getElements().size();
            }
        }else{
            return;
        }
        if (size > 3) {
            size = 3;
        }
        for (int i = 0; i < size; i++) {

            BaseElement itemData;

            if (mIsNews) {
                itemData = catData.getElements().get(i);
            } else {
                itemData = catData.getElements().get(i);
            }

            IViewItem item = ViewItemFactory.getInstance().getViewItem(itemData.getLayout(), getActivity());
            item.setData(itemData);

            int width = getDimenPixel(R.dimen.d_278dp);
            if (i == 0) {
                width = getDimenPixel(R.dimen.d_575dp);
            }
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width, getDimenPixel(R.dimen.d_260dp));
            int marginValue = getDimenPixel(R.dimen.d_11dp);
            params.leftMargin = marginValue;
            params.rightMargin = marginValue;
            ((View) item).setFocusable(true);
            mFirstRecommend.addView((View) item, params);
        }
        if (mFirstRecommend.getChildCount() != 0) {
            isFinishInit = true;
            mFirstRecommend.setVisibility(View.VISIBLE);
            if(!FragmentBlockHeader.headerFocused){
                mFirstRecommend.setSelectedViewIndex(mFirstRecommend.getChildCount()-1);
                mFirstRecommend.requestFocus();
            }
        }
    }

    private void initSecondRecommendData(String url) {
        final String mUrl = url+"&page=1&psize=20";
        final WasuCacheModule wasuCacheModule = WasuCacheModule.getInstance();
        CatData mCatData = (CatData) wasuCacheModule.getAsObject(mUrl);
        if (mCatData != null){
            if (mIsNews) {
                mSecondElements.addAll(mCatData.getElements());
            } else {
                if (mCatData.getAssets().size() > 0) {
                    mSecondElements.addAll(mCatData.getAssets());
                } else {
                    mSecondElements.addAll(mCatData.getElements());
                }
            }
            showSecondRecommendData();
            CatProtocol.fetchData(getHandler(), mUrl, new CatProtocol.CatFetchCallback() {
                @Override
                public void onResult(boolean successed, CatData catData) {
                    if (catData != null) {
                        wasuCacheModule.remove(mUrl);
                        wasuCacheModule.put(mUrl ,catData);
                    }
                }
            });
        }else{
            CatProtocol.fetchData(getHandler(), mUrl, new CatProtocol.CatFetchCallback() {
                @Override
                public void onResult(boolean successed, CatData catData) {
                    if (catData != null){
                        wasuCacheModule.remove(mUrl);
                        wasuCacheModule.put(mUrl ,catData);
                        if (mIsNews) {
                            mSecondElements.addAll(catData.getElements());
                        } else {
                            if (catData.getAssets().size() > 0) {
                                mSecondElements.addAll(catData.getAssets());
                            } else {
                                mSecondElements.addAll(catData.getElements());
                            }
                        }
                    }

                    showSecondRecommendData();
                }
            });
        }
    }

    @Override
    public void onDestroyView() {
    	super.onDestroyView();
    	isFinishInit = false;
    }

    /**
     * 组织并显示第二排推荐
     */
    private void showSecondRecommendData() {
    	if (getActivity() == null) {
    		return;
    	}

        mSecondRecommend.removeAllViews();

        int size = mSecondElements.size();
        int maxSize = 6;
        if(mIsNews) {
            maxSize = 4;
        }
        if(size > maxSize) {
            size = maxSize;
        }

        for(int i = 0;i < size;i++) {
            BaseElement itemData = mSecondElements.get(i);
            ChannelMovieItem item = new ChannelMovieItem(getActivity());
            item.setData(itemData);

            int width = getDimenPixel(R.dimen.d_178dp);
            if(mIsNews) {
                width = getDimenPixel(R.dimen.d_278dp);
            }

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width,getDimenPixel(R.dimen.d_236dp));
            int marginValue = getDimenPixel(R.dimen.d_11dp);
            params.leftMargin = marginValue;
            params.rightMargin = marginValue;
            mSecondRecommend.addView(item,params);
        }
        if (mSecondRecommend.getChildCount() != 0) {
        	mSecondRecommend.setVisibility(View.VISIBLE);
        }
        
    }

    public View focusSearch(View focused,int direction) {
        View res = null;

        if(mIsAnim){
            return focused;
        }
        switch (direction) {
            case View.FOCUS_UP:
                if(!getView().hasFocus()) {
                    showSecondRecommend();
                    res = mSecondRecommend;
                } else if(mSecondRecommend.hasFocus()) {
                    if(mSecondAd.getVisibility() == View.VISIBLE) {
                        res = mSecondAd;
                    }
                    else {
                        res = mFirstRecommend;
//                        mFirstRecommend.requestFocus();
                    }
                    showFirstRecommend();
                }
                break;
            case View.FOCUS_DOWN:
                if(mSecondRecommend.hasFocus()) {
                    if(!assetGridViewItemEmpty){
                    	hideSecondRecommend();
                    	return null;
                    }else{
                    	res = mSecondRecommend;
                    }
                }
                else if(mFirstRecommend.hasFocus()){
                    if(mFirstAd.getVisibility() == View.VISIBLE) {
                        res = mSecondAd;
                    }
                    else {
                        res = mSecondRecommend;
                        hideFirstRecommend();
                    }

                } else if(mSecondAd.hasFocus()) {
                    res = mSecondRecommend;
                    hideFirstRecommend();
                }
                else if(!getView().hasFocus()){
                    res = mFirstRecommend;
                }
                break;
        }

        return res;
    }

    public boolean requestFocus(int direction,Rect previouslyFocusedRect) {
        if(mFirstRecommendVisible) {
            return mFirstRecommend.requestFocus(direction,previouslyFocusedRect);
        }
        else if(mSecondRecommendVisible) {
            return mSecondRecommend.requestFocus(direction,previouslyFocusedRect);
        }
        return false;
    }

    private void hideFirstRecommend() {
        int adHeight = mFirstAd.getVisibility() == View.VISIBLE?mFirstAd.getMeasuredHeight():0;
        int animValue = mFirstRecommend.getMeasuredHeight() + adHeight;
        mMarginValue = -animValue;
        doAnim(mMarginValue,false,mFirstRecommend);
//        mSecondRecommend.requestFocus();
        mSecondBlockRequestFocus();
        mFirstRecommendVisible = false;
        flagFocusView.setVisibility(View.INVISIBLE);
    }

    private void showFirstRecommend() {
    	mFirstRecommend.setVisibility(View.VISIBLE);
        doAnim(0,true,mFirstRecommend);
//        mFirstRecommend.requestFocus();
        mFirstBlockRequestFocus();
        mFirstRecommendVisible = true;
    }

    private void hideSecondRecommend() {
        int adHeight = mSecondAd.getVisibility() == View.VISIBLE?mSecondAd.getMeasuredHeight():0;
        int animValue = mSecondRecommend.getMeasuredHeight() + adHeight;
        mMarginValue += -animValue;
        doAnim(mMarginValue,false,mSecondRecommend);

        mSecondRecommendVisible = false;
        flagFocusView.setVisibility(View.INVISIBLE);
    }

    private void showSecondRecommend() {
    	mSecondRecommend.setVisibility(View.VISIBLE);
        int adHeight = mFirstAd.getVisibility() == View.VISIBLE?mFirstAd.getMeasuredHeight():0;
        int animValue = mFirstRecommend.getMeasuredHeight() + adHeight;
        mMarginValue = -animValue;
        doAnim(mMarginValue,true,mSecondRecommend);

        mSecondRecommendVisible = true;
    }
    /**
     * 保证焦点在第一排和第二排推荐位跳转的时候规律统一
     */
    private void mFirstBlockRequestFocus(){
    	int index = mSecondRecommend.getSelectedViewIndex();
    	if(mIsNews){
    		if(0==index || 1==index){
                setFirstRecommendSlectedIndex(0);
        		mFirstRecommend.requestFocus();
    		}else if(2==index){
                setFirstRecommendSlectedIndex(1);
        		mFirstRecommend.requestFocus();
    		}else{
                setFirstRecommendSlectedIndex(2);
        		mFirstRecommend.requestFocus();
    		}
    	}else{
    		if(5==index || 4==index){
                setFirstRecommendSlectedIndex(2);
        		mFirstRecommend.requestFocus();
        	}else if(3 == index){
                setFirstRecommendSlectedIndex(1);
        		mFirstRecommend.requestFocus();
        	}else{
                setFirstRecommendSlectedIndex(0);
        		mFirstRecommend.requestFocus();
        	}
    	}
    }	
    
    private void mSecondBlockRequestFocus(){
    	int index = mFirstRecommend.getSelectedViewIndex();
    	if(mIsNews){
    		if(0==index){
                setSecondRecommendSlectedIndex(0);
        		mSecondRecommend.requestFocus();
    		}else if(1==index){
                setSecondRecommendSlectedIndex(2);
        		mSecondRecommend.requestFocus();
    		}else{
                setSecondRecommendSlectedIndex(3);
        		mSecondRecommend.requestFocus();
    		}
    	}else{
    		if(0==index){
                setSecondRecommendSlectedIndex(0);
        		mSecondRecommend.requestFocus();
        	}else if(1==index){
                setFirstRecommendSlectedIndex(3);
        		mSecondRecommend.requestFocus();
        	}else{
                setSecondRecommendSlectedIndex(5);
        		mSecondRecommend.requestFocus();
        	}
    	}
    }

    private void setFirstRecommendSlectedIndex(int index) {
        if (mFirstRecommend.getChildCount() >= (index + 1)) {
            mFirstRecommend.setSelectedViewIndex(index);
        } else if (mFirstRecommend.getChildCount() > 0) {
            mFirstRecommend.setSelectedViewIndex(mFirstRecommend.getChildCount() - 1);
        }
    }

    private void setSecondRecommendSlectedIndex(int index) {
        if (mSecondRecommend.getChildCount() >= (index + 1)) {
            mSecondRecommend.setSelectedViewIndex(index);
        } else if (mSecondRecommend.getChildCount() > 0) {
            mSecondRecommend.setSelectedViewIndex(mSecondRecommend.getChildCount() - 1);
        }
    }

    public int getRecommendSelectedIndex(){
    	return mSecondRecommend.getSelectedViewIndex();
    }
    private void doAnim(int animValue,final boolean isShow,final View view) {
    	doAnim(ANIM_DURATION,animValue,isShow,view);
    }
    private void doAnim(int time,int animValue,final boolean isShow,final View view) {
    	mIsAnim = true;
        ObjectAnimator animator = ObjectAnimator.ofInt(mTopViewWrapper, "value",animValue);
        animator.setInterpolator(new DecelerateInterpolator());
        animator.setDuration(time).start();
        animator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
            	if(isShow){
            		view.setVisibility(View.VISIBLE);
            	}else{

            	}
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                mIsAnim = false;
                if(isShow){
                	view.setVisibility(View.VISIBLE);
                }else{
                	view.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });
    }

    class ViewWrapper {

        private View mTargetView;

        public ViewWrapper(View target) {
            mTargetView = target;
        }

        public View getTargetView() {
            return mTargetView;
        }

        public int getValue() {
        	LayoutParams layoutParams = (LayoutParams) mTargetView.getLayoutParams();
            return layoutParams.topMargin;
        }

        public void setValue(int value) {
        	LayoutParams layoutParams =  (LayoutParams) mTargetView.getLayoutParams();
            layoutParams.topMargin = value;
            mTargetView.setLayoutParams(layoutParams);
        }
    }
    
    /**
     * 带有推荐位的首页的第三排资产gridview是否为空，如果为空，第二排的推荐位就不hide
     * @param isEmpty
     */
    public void setAssetGridViewItemEmpty(boolean isEmpty){
    	this.assetGridViewItemEmpty = isEmpty;
    }
    
    @Override
    public void onDestroy() {
    	// TODO Auto-generated method stub
    	super.onDestroy();
    	cleanResource();
    }
    
    public void cleanResource(){
    	if(mFirstAd != null){
    		mFirstAd = null;
    	}
    	if(mSecondAd != null){
    		mFirstAd = null;
    	}
    	if(mFirstRecommend != null){
    		mFirstRecommend.removeAllViews();
    		mFirstRecommend = null;
    	}
    	if(mSecondRecommend != null){
    		mSecondRecommend.removeAllViews();
    		mSecondRecommend = null;
    	}
    	if(mTopViewWrapper != null){
    		mTopViewWrapper = null;
    	}
    	if(mCatData != null){
    		mCatData = null;
    	}
    	if(mSecondElements != null){
    		mSecondElements.clear();
    		mSecondElements = null;
    	}
    }
}
