package com.wasu.cs.widget.mediacontrol;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.wasu.common.WError;
import com.wasu.cs.model.DemandProgram;
import com.wasu.cs.model.IAssetList;
import com.wasu.cs.model.Recommend;
import com.wasu.cs.ui.ActivityPlayer;
import com.wasu.cs.widget.videoview.PlayerParams;
import com.wasu.cs.widget.videoview.WasuPlayerView;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.frescoimagefetchermodule.RecyclerPauseOnScrollListener;
import com.wasu.module.datafetch.DataFetchListener;
import com.wasu.module.datafetch.DataFetchModule;
import com.wasu.module.datafetch.ObjectBase;
import com.wasu.module.log.WLog;
import com.wasu.widgets.adapter.BaseFocusRecyclerViewAdapterTv;
import com.wasu.widgets.adapter.BaseFocusRecyclerViewHolderTv;
import com.wasu.widgets.focuswidget.IRecyclerView;
import com.wasu.widgets.focuswidget.TvRecyclerView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

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

/**
 * 短视频上键推荐
 *
 * Created by chenliang on 2016/12/29.
 * 2016.12.29
 */

public class RecommendMoviePanelR extends FrameLayout{

    private String TAG = "RecommendMoviePanelR";

    // DemandProgram.SHOWTYPE_MOVIE 电影带评分类型
    // DemandProgram.SHOWTYPE_NEITHER_MOVIE_NOR_TV  短视频 截帧图类型

    private int mRecommendType; // 显示的类型
    private Context mContext;
    private MediaController mediaController;

    private RecommendAdapter mAdapter;
    private TvRecyclerView mRecycleView;

    private List<Recommend.RecommendData> data = new ArrayList<Recommend.RecommendData>(); // 推荐的数据
    private boolean viewLock/**图像加载锁*/, dataLock/**数据加载锁*/;

    private IAssetList assetList;
    private String assetUrl;

    private void init(){
        getRecommendData();

        View v = LayoutInflater.from(mContext).inflate(R.layout.item_recommend_movie_panel, this);
        mRecycleView = (TvRecyclerView) v.findViewById(R.id.tvrecycleview);
        /**
         * initRecycleview
         * */
        mAdapter = new RecommendAdapter(mRecycleView);
        mRecycleView.setAdapter(mAdapter);
        mRecycleView.setClipChildren(false);
        mRecycleView.setClipToPadding(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        linearLayoutManager.setOrientation(linearLayoutManager.HORIZONTAL);
        mRecycleView.setLayoutManager(linearLayoutManager);
        mRecycleView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.left = mContext.getResources().getDimensionPixelSize(R.dimen.d_10dp);
                outRect.top = mContext.getResources().getDimensionPixelSize(R.dimen.d_10dp);
                outRect.right = mContext.getResources().getDimensionPixelSize(R.dimen.d_10dp);
                outRect.bottom = mContext.getResources().getDimensionPixelSize(R.dimen.d_10dp);
            }
        });
        mRecycleView.addOnScrollListener(new RecyclerPauseOnScrollListener(true, true)); // 滚动时不加载图片
        mAdapter.setOnItemListener(new BaseFocusRecyclerViewAdapterTv.OnItemListener() {
            @Override
            public void onItemClick(IRecyclerView parent, View itemView, int position) {
                WLog.e(TAG,"onItemClickonItemClickonItemClickonItemClickonItemClick");

                mediaController.getPlayer().stopPlayback();
                mediaController.post(new Runnable() {

                    @Override
                    public void run() {
                        mediaController.hideCurrentView();
                    }

                });

                if (assetList == null) {
                    if (getContext() instanceof ActivityPlayer) {
                        Intent intent = new Intent(ActivityPlayer.ACTION);
                        intent.putExtra(ActivityPlayer.ASSET_URL, mAdapter.getItemData(position).getJsonUrl());
                        mediaController.getContext().startActivity(intent);
                    } else {
                        PlayerParams playerParams = new PlayerParams();
                        playerParams.setAssetUrl(mAdapter.getItemData(position).getJsonUrl());
                        ((WasuPlayerView) mediaController.getPlayer()).play(playerParams);
                    }
                } else {
                    if (getContext() instanceof ActivityPlayer) {
                        Intent intent = new Intent(ActivityPlayer.ACTION);
                        intent.putExtra(ActivityPlayer.PLAY_TYPE, ActivityPlayer.PLAY_TYPE_LOOP);
                        intent.putExtra(IntentConstant.PLAY_INDEX.value(), position);
                        intent.putExtra(ActivityPlayer.ASSET_LIST, (Serializable) assetList);
                        if (mRecommendType == DemandProgram.SHOWTYPE_NEITHER_MOVIE_NOR_TV){
                            intent.putExtra(ActivityPlayer.ASSET_URL, assetUrl);
                        }
                        mediaController.getContext().startActivity(intent);
                    } else {
                        PlayerParams playerParams = new PlayerParams();
                        playerParams.setPlayType(WasuPlayerView.PLAY_TYPE_LOOP);
                        playerParams.setPlayIndex(position);
                        playerParams.setAssetList(assetList);
                        if (mRecommendType ==  DemandProgram.SHOWTYPE_NEITHER_MOVIE_NOR_TV){
                            playerParams.setAssetUrl(assetUrl);
                        }
                        ((WasuPlayerView) mediaController.getPlayer()).play(playerParams);
                    }
                }
            }

            @Override
            public void onItemFocusChanged(IRecyclerView parent, View itemView, int position, boolean hasFocus) {

            }
        });

        viewLock = true;
        if (viewLock && dataLock){
            loadSuccess();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN &&
                (event.getKeyCode() == KeyEvent.KEYCODE_DPAD_CENTER || event.getKeyCode() == KeyEvent.KEYCODE_ENTER)){
            // 单独处理确定按键
            if (mRecycleView.getFocusedChild() != null && mRecycleView.getFocusedChild().hasFocus()){
                mRecycleView.getFocusedChild().performClick();
            }
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 获取推荐资产数据
     * */
    private void getRecommendData(){
        if (mediaController == null || mediaController.getAssetInfo() == null) {
            return;
        }

        assetList = mediaController.getAssetList();
        assetUrl = mediaController.getAssetUrl();
        if (assetList == null) {
            if (mediaController.getPlayerParams() != null) {
                assetList = mediaController.getPlayerParams().getAssetList();
            }
        }

        if (assetList == null) {
            String rcmUrl = mediaController.getAssetInfo().getRecommendUrl() + "&onPlay=" + mediaController.getAssetInfo().getAssetFrom();
            DataFetchModule.getInstance().fetchObjectGet(rcmUrl, Recommend.class, new DataFetchListener.ObjectListener() {

                @Override
                public void onObjectGet(int i, String s, ObjectBase objectBase) {
                    if (i != WError.ERROR_NONE) {
                        WLog.e(TAG, "获取短视频推荐资产出错！");
                        return;
                    }

                    Recommend recommend = (Recommend) objectBase;
                    if (recommend == null) {
                        return;
                    }

                    data.addAll(recommend.getData());

                    dataLock = true;
                    if (viewLock && dataLock){
                        loadSuccess();
                    }
                }
            });
        }else {
            post(new Runnable() {
                @Override
                public void run() {
                    for (int i=0; i < assetList.getRealSize();i++){
                        data.add(new Recommend.RecommendData("","","",assetList.getJsonUrl(i),"",
                                assetList.getPicUrl(i),"", assetList.getTitle(i), "",assetList.getPoint(i)));
                    }
                    dataLock = true;
                    if (viewLock && dataLock){
                        loadSuccess();
                    }
                }
            });
        }
    }

    /**
     * view 和 数据都加载成功时
     * */
    private void loadSuccess(){
        WLog.e(TAG, "数据获取成功！mList =  " + data.toString());
        mAdapter.setData(data);
        mAdapter.notifyDataSetChanged();

//        final int pos = Integer.MAX_VALUE/2-Integer.MAX_VALUE/2%data.size();
//        mRecycleView.getLayoutManager().scrollToPosition(pos);

        // 第一个资产获取焦点
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (mRecycleView.getChildCount() > 0 && mRecycleView.getChildAt(0) != null) {
                    mRecycleView.getChildAt(0).requestFocus();
                }
            }
        }, 200);
    }

    /**
     * adapter
     * */
    private class RecommendAdapter extends BaseFocusRecyclerViewAdapterTv<Recommend.RecommendData> {
        int mCount = 0;
        public RecommendAdapter(TvRecyclerView recyclerView) {
            super(recyclerView);
        }

        @Override
        protected BaseFocusRecyclerViewHolderTv createItem(ViewGroup parent, int viewType) {

            if (mRecommendType == DemandProgram.SHOWTYPE_MOVIE) {
                View view = LayoutInflater.from(mContext).inflate(R.layout.media_controller_prompt_footer_movie_recommendr, null);
                MovieViewHolder viewHolder = new MovieViewHolder(view);
                return viewHolder;

            }else if (mRecommendType == DemandProgram.SHOWTYPE_NEITHER_MOVIE_NOR_TV){
                View view = LayoutInflater.from(mContext).inflate(R.layout.media_controller_prompt_footer_video_recommendr, null);
                ShortViewHolder viewHolder = new ShortViewHolder(view);
                return viewHolder;

            }else {
                WLog.e(TAG, "播放器资产推荐传入的类型有误！");
                return null;
            }
        }


        @Override
        protected void bindData(BaseFocusRecyclerViewHolderTv holder, int position) {
            if (mRecommendType == DemandProgram.SHOWTYPE_MOVIE){ // 电影类型
                SimpleDraweeView img = ((MovieViewHolder)holder).img;
                TextView title = ((MovieViewHolder) holder).title;
                TextView point = ((MovieViewHolder) holder).point;

                if (getItemData(position) != null){
                    FrescoImageFetcherModule.getInstance().attachImage(
                            getItemData(position).getPicUrl()==null?"":getItemData(position).getPicUrl(),img);
                    title.setText(getItemData(position).getTitle()==null?"":getItemData(position).getTitle());
                    point.setText(getItemData(position).getPoints()==null?"":getItemData(position).getPoints());
                }else {
                    img.setBackgroundResource((R.drawable.default_wasu_bg));
                    title.setText("");
                    point.setText("");
                }

            }else if (mRecommendType == DemandProgram.SHOWTYPE_NEITHER_MOVIE_NOR_TV){ // 短视频类型
                SimpleDraweeView img = ((ShortViewHolder)holder).img;
                TextView title = ((ShortViewHolder) holder).title;

                if (getItemData(position) != null){
                    FrescoImageFetcherModule.getInstance().attachImage(
                            getItemData(position).getPicUrl()==null?"":getItemData(position).getPicUrl(),img);
                    title.setText(getItemData(position).getTitle()==null?"":getItemData(position).getTitle());
                }else {
                    img.setBackgroundResource((R.drawable.default_wasu_bg));
                    title.setText("");
                }
            }
        }

        @Override
        public Recommend.RecommendData getItemData(int position) {
            return super.getItemData(position%mCount);
        }

        @Override
        public void setData(List<Recommend.RecommendData> data) {
            mCount = data.size();
            super.setData(data);
        }

        @Override
        public int getItemCount() {
            if (mCount == 0){
                return 0;
            }else {
                return Integer.MAX_VALUE;//用于循环
            }
        }

        /**
         * 电影类型的viewHolder
         * */
        class MovieViewHolder extends BaseFocusRecyclerViewHolderTv{
            View view;
            TextView title; // 标题
            TextView point; // 评分
            SimpleDraweeView img;

            /**
             * 创建FocusRecyclerView的itemView
             *
             * @param itemView        item View
             */
            public MovieViewHolder(View itemView) {
                super(itemView, getItemParent(), getItemListener());
                view = itemView;
                img = (SimpleDraweeView) view.findViewById(R.id.pic);
                title = (TextView) view.findViewById(R.id.title);
                point = (TextView) view.findViewById(R.id.point);
            }

            @Override
            protected View getView() {
                return view;
            }
        }


        /**
         * 短视频类型的viewHolder
         * */
        class ShortViewHolder extends BaseFocusRecyclerViewHolderTv{
            View view;
            TextView title; // 标题
            SimpleDraweeView img;

            /**
             * 创建FocusRecyclerView的itemView
             *
             * @param itemView          item View
             */
            public ShortViewHolder(View itemView) {
                super(itemView, getItemParent(), getItemListener());
                view = itemView;
                img = (SimpleDraweeView) view.findViewById(R.id.pic);
                title = (TextView) view.findViewById(R.id.title);
            }

            @Override
            protected View getView() {
                return view;
            }
        }
    }

    public RecommendMoviePanelR(Context context, MediaController mediaController, int recommendType) {
        super(context);
        mRecommendType = recommendType;
        mContext = context;
        this.mediaController = mediaController;
        init();
    }
}
