package com.wasu.cs.widget.mediacontrol.adapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.wasu.common.WError;
import com.wasu.cs.model.DemandRecommand;
import com.wasu.cs.model.RecommendListEntry;
import com.wasu.cs.utils.BitmapUtils;
import com.wasu.cs.widget.mediacontrol.IMediaController;
import com.wasu.cs.widget.mediacontrol.IMediaControllerChildView;
import com.wasu.cs.widget.mediacontrol.MediaController;
import com.wasu.cs.widget.videoview.WasuLivePlayerView;
import com.wasu.cs.widget.videoview.WasuPlayerView;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
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.BaseFocusRecyclerViewAdapter;
import com.wasu.widgets.adapter.BaseFocusRecyclerViewHolder;
import com.wasu.widgets.focuswidget.FocusRecyclerView;

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

import basic.BuilderTypeManager.BuildType;
import cn.com.wasu.main.AppUtil;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;

import static cn.com.wasu.main.R.id.BottomView;

/**
 * 播放器退出资产推荐
 * @auther chenliang
 */

public class PromptExitAsset extends FrameLayout implements IMediaControllerChildView<IMediaController>, View.OnFocusChangeListener {

    private IMediaController mediaController;
    private boolean hideFlag;

    //view
    private TextView mCanel, mAgain;
    private FocusRecyclerView mRecycleView;
    private LinearLayout mLayoutUp, mLayoutDown;

    private RecommendAdapter mAdapter;
    private Context context;

    // 背景图
    private Bitmap mBackUp, mBackDown; // 前后背景图

    private static String TAG = "PromptExitAsset";
    private List<RecommendListEntry> mList;
    /**
     * 网络数据请求重试次数
     **/
    private int fetchDataRetryCount = 3;

    private void init(Context context) {
        setId(MediaController.generateID());
        LayoutInflater.from(context).inflate(R.layout.media_controller_aeest_exit, this);
        this.context = context;

        mList = new ArrayList<>();

        mCanel = (TextView) findViewById(R.id.exit);
        mAgain = (TextView) findViewById(R.id.again);
        mRecycleView = (FocusRecyclerView) findViewById(R.id.recycleview);

        mLayoutUp = (LinearLayout) findViewById(R.id.layout_up);
        mBackUp = BitmapUtils.readBitMapByDecodeStream(this.context, R.drawable.background_up);
        mLayoutUp.setBackgroundDrawable(new BitmapDrawable(this.context.getResources(), mBackUp));

        mLayoutDown = (LinearLayout) findViewById(R.id.layout_down);
        mBackDown = BitmapUtils.readBitMapByDecodeStream(this.context, R.drawable.background_down);
        mLayoutDown.setBackgroundDrawable(new BitmapDrawable(this.context.getResources(), mBackDown));

        mCanel.setOnFocusChangeListener(this);
        mAgain.setOnFocusChangeListener(this);


        /**
         * initRecycleview
         * **/
        mAdapter = new RecommendAdapter(mRecycleView);
        mRecycleView.setAdapter(mAdapter);
        mRecycleView.setNextFocusDownId(mCanel.getId());
        mRecycleView.setClipChildren(true);
        mRecycleView.setClipToPadding(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.context);
        linearLayoutManager.setOrientation(GridLayoutManager.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 = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_10dp);
                outRect.top = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_10dp);
                outRect.right = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_10dp);
                outRect.bottom = getResources().getDimensionPixelSize(cn.com.wasu.main.R.dimen.d_10dp);
            }
        });
        mAdapter.setOnItemListener(new BaseFocusRecyclerViewAdapter.OnItemListener() {
            @Override
            public void onItemClick(int position) {
                AppUtil.playEnter = "退出页推荐位";

                Intent intent = new Intent();
                IntentMap.startIntent(getContext(), intent, mList.get(position).getLayout(), mList.get(position).getJsonUrl(), null);
            }

            @Override
            public void onItemLongClick(int position) {

            }

            @Override
            public void onItemFocusChange(View itemView, int position, boolean hasFocus) {
                View bottom = itemView.findViewById(R.id.BottomView);
                if (bottom != null) {
                    if (hasFocus) {
                        bottom.setVisibility(VISIBLE);
                    } else {
                        bottom.setVisibility(INVISIBLE);
                    }
                }
            }
        });
    }


    @SuppressLint("NewApi")
    @Override
    public void onShow(IMediaController mediaController) {
        this.mediaController = mediaController;

        getRecommendData();//获取数据
        if (mAgain != null)
            mAgain.requestFocus();
    }

    @Override
    public void onHide(IMediaController mediaController) {
        hideFlag = false;
    }

    /**
     * 按键控制
     */
    @Override
    public boolean onShield(KeyEvent event) {
        boolean ret = false;
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (event.getKeyCode()) {
                case KeyEvent.KEYCODE_DPAD_LEFT:
                    if (mAgain.isFocused()) {
                        mCanel.requestFocus();
                    } else if (mRecycleView.hasFocus()) {
                        for (int i = 0; i < mRecycleView.getChildCount(); i++) {
                            View v = mRecycleView.getChildAt(i);
                            if (v != null && v.hasFocus()) {
                                View vr = mRecycleView.getChildAt(i - 1 >= 0 ? i - 1 : mRecycleView.getChildCount() - 1);
                                if (vr != null) {
                                    vr.requestFocus();
                                    break;
                                }
                            }
                        }
                    }
                    ret = true;
                    break;
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    if (mCanel.isFocused()) {
                        mAgain.requestFocus();
                    } else if (mRecycleView.hasFocus()) {
                        for (int i = 0; i < mRecycleView.getChildCount(); i++) {
                            View v = mRecycleView.getChildAt(i);
                            if (v != null && v.hasFocus()) {
                                View vr = mRecycleView.getChildAt(i + 1 < mRecycleView.getChildCount() ? i + 1 : 0);
                                if (vr != null) {
                                    vr.requestFocus();
                                    break;
                                }
                            }
                        }
                    }
                    ret = true;
                    break;
                case KeyEvent.KEYCODE_VOLUME_UP:
                case KeyEvent.KEYCODE_VOLUME_DOWN:
                case KeyEvent.KEYCODE_VOLUME_MUTE:
                case KeyEvent.KEYCODE_MENU:
                    ret = true;
                    break;

                case KeyEvent.KEYCODE_DPAD_UP:
                    if (mCanel.hasFocus() || mAgain.hasFocus()) {
                        mRecycleView.requestFocus();
                    }
                    ret = true;
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    if (mRecycleView.hasFocus()) {
                        mCanel.requestFocus();
                    }
                    ret = true;
                    break;

                case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_ENTER:
                    hideFlag = true;

                    // 退出
                    if (mCanel.isFocused() && getVisibility() == VISIBLE) {
                        mediaController.getPlayer().stopPlayback();
                        mediaController.clear();
                        ((ViewGroup) mediaController).removeAllViews();

                        ((Activity) getContext()).finish();
                    } else if (mAgain.isFocused() && getVisibility() == VISIBLE) { // 再看看
                        if (mediaController.getPlayer() instanceof WasuPlayerView || mediaController.getPlayer() instanceof WasuLivePlayerView) {
                            ((View) mediaController).post(new Runnable() {

                                @Override
                                public void run() {
                                    mediaController.hideCurrentView();
                                }
                            });
                            ((View) mediaController.getPlayer()).requestFocus();
                        }
                    } else if (mRecycleView.hasFocus() && getVisibility() == VISIBLE) { // 推荐位
                        for (int i = 0; i < mRecycleView.getChildCount(); i++) {
                            View v = mRecycleView.getChildAt(i);
                            if (v != null && v.hasFocus()) {
                                v.performClick();
                            }
                        }
                    }
                    break;
                case KeyEvent.KEYCODE_BACK:
                    hideFlag = true;

                    if (mediaController.getPlayer() instanceof WasuPlayerView || mediaController.getPlayer() instanceof WasuLivePlayerView) {
                        ((View) mediaController.getPlayer()).requestFocus();
                    }

                    break;
                default:
                    ret = true;
                    break;
            }
        }
        return ret;
    }


    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        mCanel.setTextColor(0xffffffff);
        mAgain.setTextColor(0xffffffff);

        if (hasFocus) {
            switch (v.getId()) {
                case R.id.exit:
                    mCanel.setTextColor(0xffffff00);
                    break;
                case R.id.again:
                    mAgain.setTextColor(0xffffff00);
                    break;
            }
        }
    }

    @Override
    public boolean isAutoHide() {
        return hideFlag;
    }

    /**---------------------------自定义方法非重写--------------------------------------------------**/

    /**
     * 网络请求
     */
    private synchronized void getRecommendData() {
        DataFetchListener.ObjectListener objectListener = new DataFetchListener.ObjectListener() {
            @Override
            public void onObjectGet(int retcode, String extraMsg, ObjectBase data) {

                // 重试检查
                if (retcode == WError.ERROR_INVALID_DATA || retcode == WError.ERROR_NET) {
                    if (fetchDataRetryCount > 0) {
                        DataFetchModule.getInstance().fetchObjectGet(BuildType.Exit_Recommend_Data, DemandRecommand.class, this);
                        fetchDataRetryCount--;
                        return;
                    }
                }

                if (retcode != 0) {
                    WLog.e(TAG, extraMsg+"");
                    mAgain.requestFocus();
                    return;
                }
                fetchDataRetryCount = 3;
                RecommendListEntry listEntry = (RecommendListEntry) data;
                mList.clear();

                if (listEntry.getmList() != null && listEntry.getmList().size() > 0) {
                    mList.addAll(listEntry.getmList());
                    loadDataSuccess();
                }

                mAgain.requestFocus();

            }
        };

//        WLog.e(TAG, "开始获取数据");
        DataFetchModule.getInstance().fetchObjectGet(BuildType.Exit_Recommend_Data, RecommendListEntry.class, objectListener);
    }

    /**
     * 推荐数据获取成功
     **/
    private void loadDataSuccess() {
//        WLog.e(TAG, "数据获取成功！mList =  " + mList.toString());
        mAdapter.setData(mList);
        mAdapter.notifyDataSetChanged();

    }

    /**
     * adapter
     */
    private class RecommendAdapter extends BaseFocusRecyclerViewAdapter<RecommendListEntry> {
        public RecommendAdapter(FocusRecyclerView recyclerView) {
            super(recyclerView);
        }

        @Override
        protected BaseFocusRecyclerViewHolder createItem(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(context).inflate(R.layout.activity_exit_item, null);
            MyViewHolder viewHolder = new MyViewHolder(view, getItemParent(), getItemListener());
            return viewHolder;
        }

        @Override
        protected void bindData(BaseFocusRecyclerViewHolder holder, int position) {
            SimpleDraweeView img = ((MyViewHolder) holder).img;
            TextView title = ((MyViewHolder) holder).title;
            TextView point = ((MyViewHolder) holder).point; // point字段暂缺

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


        // viewHolder
        public class MyViewHolder extends BaseFocusRecyclerViewHolder {
            View view;
            SimpleDraweeView img;
            RelativeLayout bottomView; //底部view
            TextView title; // 标题
            TextView point; // 评分

            /**
             * 创建FocusRecyclerView的itemView
             *
             * @param itemView          item View
             * @param focusRecyclerView item parent ViewGroup(Parent must instanceof FocusRecyclerView)
             * @param mOnItemListener   item click、longClick、focusChange listener
             */
            public MyViewHolder(View itemView, FocusRecyclerView focusRecyclerView, OnItemListener mOnItemListener) {
                super(itemView, focusRecyclerView, mOnItemListener);
                view = itemView;
                img = (SimpleDraweeView) view.findViewById(R.id.img);
                bottomView = (RelativeLayout) view.findViewById(BottomView);
                title = (TextView) view.findViewById(R.id.title);
                point = (TextView) view.findViewById(R.id.point);
            }

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

    /**
     * ------------------------------------------------------
     **/
    public PromptExitAsset(Context context) {
        super(context);
        init(context);
    }

    public PromptExitAsset(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public PromptExitAsset(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }


    @Override
    public void onAdStatusChanged(int arg0, int arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onCompletion(MediaPlayer arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onError(MediaPlayer arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onInfo(MediaPlayer arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPause(MediaPlayer arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPrepareComplete(MediaPlayer arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPreparing(MediaPlayer arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProgress(int arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onResume(MediaPlayer arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSeekComplete(MediaPlayer arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onSeeking(MediaPlayer arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStart(MediaPlayer arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(MediaPlayer arg0, int arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStop(MediaPlayer arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onWasuError(int arg0, String arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onWasuPlayLimit(int arg0, String arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void setRelativeViews(IMediaControllerChildView<IMediaController>... views) {
        // TODO Auto-generated method stub

    }

    @Override
    public List<IMediaControllerChildView<IMediaController>> getRelativeViews() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void clear() {
        // TODO Auto-generated method stub
    }
}
