package com.wasu.cs.adapter;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.model.FocusNewSeries;
import com.wasu.cs.module.ChildFavModule;
import com.wasu.cs.ui.ActivityChildrenDetail;
import com.wasu.cs.ui.ActivityPlayer;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.module.datafetch.DataFetchListener.ObjectListener;
import com.wasu.module.datafetch.DataFetchModule;
import com.wasu.module.datafetch.ObjectBase;

import java.util.List;

import basic.BuilderTypeManager.BuildType;
import basic.db.model.DBProgramChildFavorite;
import cn.com.wasu.main.BuildConfig;
import cn.com.wasu.main.ChannelFlavor;
import cn.com.wasu.main.Common;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;

/**
 * Created by jeepc
 */
public class ChildFavRecyclerAdapter extends
        RecyclerView.Adapter<ChildFavRecyclerAdapter.ViewHolder> {


    // 数据集
    private List<DBProgramChildFavorite> mFavList;
    private Context mContext;

    private OnItemFocusChangeListener mOnItemFocusChangeListener;
    private OnItemDeleteListener mOnItemDeleteListener;

    public void setOnItemFocusChangeListener(OnItemFocusChangeListener onItemFocusChangeListener) {
        this.mOnItemFocusChangeListener = onItemFocusChangeListener;
    }

    public void setOnItemClickListener(OnItemDeleteListener onItemDeleteListener) {
        this.mOnItemDeleteListener = onItemDeleteListener;
    }


    private int mIndex = 0;

    public void setIndex(int index) {
        this.mIndex = index;
    }

    public int getIndex() {
        return mIndex;
    }


    public ChildFavRecyclerAdapter(Context context, List<DBProgramChildFavorite> favList, int index) {
        super();
        this.mContext = context;
        this.mFavList = favList;
        this.mIndex = index;
    }


    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, final int i) {
        View view = View.inflate(viewGroup.getContext(), R.layout.item_children_fav,
                null);
        ViewHolder holder = new ViewHolder(view);

        return holder;
    }


    @Override
    public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
        final DBProgramChildFavorite myFav = mFavList.get(i);

        // 绑定数据到ViewHolder上
        setData(viewHolder, i, myFav);
        //追剧
        bingeWatching(viewHolder, myFav);

        //item点击事件
        viewHolder.itemContentlayout.setOnClickListener(getItemClickListener(i));
        //item按键事件
        viewHolder.itemContentlayout.setOnKeyListener(getKeyClickListener(i));
        //item焦点监听
        viewHolder.itemContentlayout.setOnFocusChangeListener(getItemFocusChangeListener(viewHolder, i));
        //del焦点监听
        viewHolder.delTextView.setOnFocusChangeListener(getDelFocusChangeListener(viewHolder));
        //del点击事件
        viewHolder.delTextView.setOnClickListener(getDelClickListener(viewHolder, i));

    }

    //绑定数据
    private void setData(ViewHolder viewHolder, int i, DBProgramChildFavorite myFav) {

        if (TextUtils.isEmpty(myFav.programPic)) {
            viewHolder.picImageView.setBackgroundResource(R.drawable.default_pic_loading);
        } else {
            FrescoImageFetcherModule.getInstance().attachImage(myFav.programPic,
                    viewHolder.picImageView, (int) mContext.getResources().getDimension(R.dimen.d_7dp));
        }
        viewHolder.nameTextView.setText(myFav.programName);
        viewHolder.nameTextView.setVisibility(View.VISIBLE);
        if (myFav.showType == 3) {
            if (myFav.showType == DemandProgram.SHOWTYPE_TV_SERIES) {
                viewHolder.infoTextView.setText("已更新至" + myFav.updateSeries + "集");
            } else {
                viewHolder.infoTextView.setText("全" + myFav.totalSeries + "集");
            }
            viewHolder.infoTextView.setVisibility(View.VISIBLE);
        }

        viewHolder.getView().setTag(i);
    }

    //数据回调
    private ObjectListener getObjectListener(final ViewHolder viewHolder, final DBProgramChildFavorite myFav) {
        return new ObjectListener() {

            @Override
            public void onObjectGet(int retcode, String extraMsg,
                                    ObjectBase data) {
                if (retcode != 0) {
                    return;
                }
                FocusNewSeries focusNewSeries = (FocusNewSeries) data;
                if (focusNewSeries.getFocusNew().size() > 0) {
                    // 获得当前更新到哪一集
                    int currentserval = focusNewSeries
                            .getFocusNew().get(0)
                            .getCurrentServal();
                    // 数据库中上次更新的电视剧集数小于当前更新集数，则替换上次更新的集数，并现实追剧
                    if (myFav.updateSeries < currentserval) {
                        myFav.updateSeries = currentserval;
                        ChildFavModule.getInstance().saveFavorite(
                                myFav);
                        viewHolder.newsetView
                                .setVisibility(View.VISIBLE);
                    } else {
                        if (myFav.preUpdateSeries < myFav.updateSeries) {// 上次更新后用户没看过，继续显示追剧
                            viewHolder.newsetView
                                    .setVisibility(View.VISIBLE);
                        } else {
                            viewHolder.newsetView
                                    .setVisibility(View.GONE);
                        }
                    }
                }

            }
        };
    }

    //追剧
    private void bingeWatching(ViewHolder viewHolder, DBProgramChildFavorite myFav) {
        if (myFav.preUpdateSeries < myFav.updateSeries) {// 上次更新后用户没看过，继续显示追剧
            viewHolder.newsetView.setVisibility(View.VISIBLE);
        } else {
            viewHolder.newsetView.setVisibility(View.GONE);
        }
        // 追剧
        if (myFav.showType == 3
                && myFav.updateSeries < myFav.totalSeries) {// 数据库中上次更新的电视剧集数小于总集数，请求追剧
            String url = Common.FOCUS_URL + myFav.programId + (BuildConfig.FLAVOR.equalsIgnoreCase(ChannelFlavor.LETV_MARKET) ? "&c=" + BuildType.ChannelId : "");

            DataFetchModule.getInstance().fetchObjectGet(url,
                    FocusNewSeries.class, getObjectListener(viewHolder, myFav));
        } else {
            viewHolder.newsetView.setVisibility(View.GONE);
        }
    }

    //item监听
    private OnFocusChangeListener getItemFocusChangeListener(final ViewHolder viewHolder, final int i) {
        OnFocusChangeListener listener = new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    scaleView(viewHolder.itemView, 1.1f);
                    viewHolder.nameTextView.setSelected(true);
                    viewHolder.delTextView.setVisibility(View.VISIBLE);
                    if (mOnItemFocusChangeListener != null) {
                        mOnItemFocusChangeListener.onItemFocusChange((ViewGroup) viewHolder.itemView, i, true, mIndex);
                    }
                } else {

                    viewHolder.nameTextView.setSelected(false);

                }
            }
        };


        return listener;
    }


    private void scaleView(View view, float scale) {
        view.setScaleX(scale);
        view.setScaleY(scale);
    }

    //item点击事件
    private OnClickListener getItemClickListener(final int i) {
        return new OnClickListener() {

            @Override
            public void onClick(View v) {
                DBProgramChildFavorite fav = mFavList.get(i);
                if (fav.preUpdateSeries < fav.updateSeries) {
                    fav.preUpdateSeries = fav.updateSeries;
                    ChildFavModule.getInstance().saveFavorite(fav);
                }
                Intent intent = new Intent();
                IntentMap.startIntent(mContext, intent, null, fav.detailUrl, ActivityChildrenDetail.class);

            }
        };
    }


    private View.OnKeyListener getKeyClickListener(final int i) {
        return new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (i == getItemCount() - 1 && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                    return true;
                }
                return false;
            }
        };
    }

    //del焦点监听
    private OnFocusChangeListener getDelFocusChangeListener(final ViewHolder viewHolder) {
        return new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    viewHolder.delTextView.setVisibility(View.VISIBLE);
                } else {
                    viewHolder.delTextView.setVisibility(View.GONE);
                }
            }
        };
    }

    //del点击事件
    private OnClickListener getDelClickListener(final ViewHolder viewHolder, final int i) {
        return new OnClickListener() {

            @Override
            public void onClick(View v) {
                ChildFavModule.getInstance().deleteFavorite(mFavList.get(i).programId + "");
                mFavList.remove(i);
                if (getItemCount() == 0) {
                    if (mOnItemDeleteListener != null) {
                        mOnItemDeleteListener.onAllItemDelete();
                    }
                    return;
                }
                notifyItemRemoved(i);
                scaleView(viewHolder.itemContentlayout, 1F);
                if (i < getItemCount()) notifyItemRangeChanged(i, getItemCount());
                int pos = i;
                if (i == getItemCount()) --pos;
                if (mOnItemDeleteListener != null) {
                    mOnItemDeleteListener.onItemDelete(pos, mIndex);
                }

            }
        };
    }


    @Override
    public int getItemCount() {
        return mFavList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public View view;
        public RelativeLayout itemContentlayout;
        public ImageView picImageView;
        public View newsetView;
        public TextView nameTextView;
        public TextView infoTextView;
        public TextView delTextView;

        public ViewHolder(View itemView) {
            super(itemView);
            this.view = itemView;
            itemContentlayout = (RelativeLayout) itemView
                    .findViewById(R.id.content_layout);
            picImageView = (ImageView) itemView
                    .findViewById(R.id.pic);
            newsetView = itemView.findViewById(R.id.newset);
            nameTextView = (TextView) itemView
                    .findViewById(R.id.name);
            infoTextView = (TextView) itemView
                    .findViewById(R.id.info);
            delTextView = (TextView) itemView
                    .findViewById(R.id.del);
        }

        public View getView() {
            return view;
        }
    }


}
