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.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.model.FocusNewSeries;
import com.wasu.cs.module.FavAndHisModule;
import com.wasu.cs.ui.ActivityDetail;
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 com.wasu.module.db.DBBase;

import java.util.List;

import basic.BuilderTypeManager.BuildType;
import basic.db.model.DBProgramHistory;
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 stone.
 */
public class HisRecyclerAdapter<T extends DBBase>extends
        RecyclerView.Adapter<HisRecyclerAdapter.ViewHolder> {


    // 数据集
    private List<DBBase> mhistoryList;
    private Context context;


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

    public int getIndex() {
        return mIndex;
    }

    private OnItemFocusChangeListener mOnItemFocusChangeListener;
    private OnItemDeleteListener mOnItemDeleteListener;

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

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


    public HisRecyclerAdapter(List<DBBase> mhistoryList,
                              Context context) {
        super();
        this.mhistoryList = mhistoryList;
        this.context = context;
    }


    public HisRecyclerAdapter(List<DBBase> mhistoryList,
                              Context context, int index) {
        super();
        this.mhistoryList = mhistoryList;
        this.context = context;
        this.mIndex = index;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, final int i) {
        // 创建一个View
        View view = View.inflate(viewGroup.getContext(), R.layout.item_his,
                null);
        // 创建一个ViewHolder
        ViewHolder holder = new ViewHolder(view);

        return holder;
    }


    @Override
    public void onBindViewHolder(final ViewHolder viewHolder, final int i) {
        final DBProgramHistory myHistory = (DBProgramHistory) mhistoryList.get(i);

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

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

    }

    //绑定数据
    private void setData(ViewHolder viewHolder, int i, DBProgramHistory myHistory) {
        if (TextUtils.isEmpty(myHistory.programPic)) {
            viewHolder.picImageView.setBackgroundResource(R.drawable.default_pic_loading);
        } else {
            FrescoImageFetcherModule.getInstance().attachImage(myHistory.programPic,
                    viewHolder.picImageView);
        }
        viewHolder.titleTextView.setVisibility(View.VISIBLE);
        if (myHistory.showType == DemandProgram.SHOWTYPE_TV_SERIES) {
            viewHolder.titleTextView.setText(myHistory.programName + " 第" + (myHistory.lastSeries) + "集");
        } else {
            viewHolder.titleTextView.setText(myHistory.programName);
        }

        viewHolder.timeProgress.setVisibility(View.VISIBLE);
        int progress = (int) ((double) myHistory.lastPlayTime / myHistory.duration * 100);
        viewHolder.timeProgress.setProgress(progress);
        viewHolder.getView().setTag(i);
    }

    //数据回调
    private ObjectListener getObjectListener(final ViewHolder viewHolder, final DBProgramHistory myHistory) {
        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 (myHistory.updateSeries < currentserval) {
                        myHistory.updateSeries = currentserval;
                        FavAndHisModule.getInstance().saveHistory(
                                myHistory);
                        viewHolder.focusnewTextView
                                .setVisibility(View.VISIBLE);
                    } else {
                        if (myHistory.preUpdateSeries < myHistory.updateSeries) {// 上次更新后用户没看过，继续显示追剧
                            viewHolder.focusnewTextView
                                    .setVisibility(View.VISIBLE);
                        } else {
                            viewHolder.focusnewTextView
                                    .setVisibility(View.GONE);
                        }
                    }
                } else {// 无数据，代表下线
                    viewHolder.focusnewTextView
                            .setVisibility(View.GONE);
                    return;
                }

            }
        };
    }

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

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

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


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

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    viewHolder.titleTextView.setSelected(true);
                    viewHolder.timeProgress.setVisibility(View.GONE);
                    viewHolder.timeTextView.setVisibility(View.VISIBLE);
                    viewHolder.timeTextView.setText("已观看"
                            + getTextTime(myHistory.lastPlayTime));
                    viewHolder.delTextView.setVisibility(View.VISIBLE);
                    if (mOnItemFocusChangeListener != null) {
                        mOnItemFocusChangeListener.onItemFocusChange((ViewGroup) viewHolder.itemView, i, true, mIndex);
                    }
                    scaleView(viewHolder.itemView,1.1f);
                } else {

                    viewHolder.timeProgress.setVisibility(View.VISIBLE);
                    viewHolder.timeTextView.setVisibility(View.GONE);
                    viewHolder.titleTextView.setSelected(false);

                }
            }
        };


        return listener;
    }


    private long mLastKeyDownTime = 0;
    private View.OnKeyListener getKeyClickListener(final int i) {
        return new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT||keyCode ==KeyEvent.KEYCODE_DPAD_LEFT && event.getAction() == KeyEvent.ACTION_DOWN) {
                    long current = System.currentTimeMillis();
                    if (current - mLastKeyDownTime < 160) {
                        return true;
                    } else {
                        mLastKeyDownTime = current;
                    }
                }
                if (i == getItemCount() - 1 && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                    return true;
                }
                if(i == 0 && keyCode == KeyEvent.KEYCODE_DPAD_LEFT&&event.getAction()==KeyEvent.ACTION_DOWN){
                    if (mOnItemFocusChangeListener != null) {
                        mOnItemFocusChangeListener.onFirstItemFocusLeft();
                    }
                    return true;
                }
                return false;
            }
        };
    }

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

            @Override
            public void onClick(View v) {
                DBProgramHistory history = (DBProgramHistory) mhistoryList.get(i);
                if (history.showType == 0) {
                    Intent intent = new Intent();
                    IntentMap.startIntent(context, intent, null, history.detailUrl, ActivityPlayer.class);
                } else {
                    if (history.preUpdateSeries < history.updateSeries) {
                        history.preUpdateSeries = history.updateSeries;
                        FavAndHisModule.getInstance().saveHistory(history);
                        viewHolder.focusnewTextView.setVisibility(View.GONE);
                    }
                    Intent intent = new Intent();
                    IntentMap.startIntent(context, intent, null, history.detailUrl, ActivityDetail.class);
                }

            }
        };
    }

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

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

            @Override
            public void onClick(View v) {
                FavAndHisModule.getInstance().deleteHistory(((DBProgramHistory)mhistoryList.get(i)).programId + "");
                mhistoryList.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);
                }

            }
        };
    }



    private String getTextTime(long time) {

        long sec = Math.round(time / 1000.0);//显示少一秒
        long min = sec / 60;
        long hour = min / 60;


        if (min > 0) {
            if (hour > 0) {
                min = (sec - hour*60*60)/60;
                sec = (sec - hour*60*60)%60;
                return hour + "小时" + min + "分" + sec + "秒";
            } else {
                sec = sec%60;
                return min + "分" + sec + "秒";
            }
        } else {
            return sec + "秒";
        }
    }

    private String getformat(long time) {
        if (time < 10) {
            return "0" + time;
        } else {
            return time + "";
        }
    }



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

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public View view;
        public RelativeLayout itemContentlayout;
        public ImageView picImageView;
        public TextView titleTextView;
        public TextView timeTextView;
        public TextView focusnewTextView;
        public ProgressBar timeProgress;
        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);
            titleTextView = (TextView) itemView
                    .findViewById(R.id.title);
            timeTextView = (TextView) itemView
                    .findViewById(R.id.playtime);
            focusnewTextView = (TextView) itemView
                    .findViewById(R.id.find_new);
            timeProgress = (ProgressBar) itemView
                    .findViewById(R.id.timeprogress);
            delTextView = (TextView) itemView
                    .findViewById(R.id.del);
        }

        public View getView() {
            return view;
        }
    }


}
