package com.wasu.cs.widget;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;

import com.facebook.drawee.view.SimpleDraweeView;
import com.wasu.comp.videoview.IMediaListener;
import com.wasu.cs.model.HomeColumnModel;
import com.wasu.cs.model.SpecialColumnModel.ChannelListModel;
import com.wasu.cs.mvp.model.AssetsDataModel;
import com.wasu.cs.widget.mediacontrol.MediaController;
import com.wasu.cs.widget.videoview.WasuLivePlayerView;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.module.log.WLog;
import com.wasu.module.msgqueue.MsgHandler;
import com.wasu.module.msgqueue.MsgIdConstant;
import com.wasu.module.msgqueue.MsgQueueModule;
import com.wasu.statistics.WasuStatistics;

import java.util.List;

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

/**
 * @Description: 首页推荐屏的视频小窗口,对直播播放器再封装！
 *
 * @Author: Danxingxi
 *
 * @CreateDate: 2016/9/5 15:35
 */
public class MainPageLiveVideoView extends RelativeLayout implements IMediaListener, MsgHandler,
        View.OnClickListener {
    private static final String TAG = MainPageLiveVideoView.class.getSimpleName();
    /**视频窗口获得焦点后延时多长时间开始播放视频**/
    private static final long delayedTime = 2000;

    private static final int ACTION_IDLE = 1 << 0;
    private static final int ACTION_PLAY = 1 << 1;
    private static final int ACTION_PREPARE = 1 << 2;
    private static final int ACTION_PAUSE = 1 << 3;
    private static final int ACTION_RESUME = 1 << 4;
    private static final int ACTION_STOP = 1 << 5;
    private String layout;
    private String jsonUrl;
    /**运营图片**/
    private String firstImgUrl;
    /**封装好的直播播放器**/
    private WasuLivePlayerView mVideoView;
    /**轮播数据**/
    private ChannelListModel channel = null;
    /**播放器数据**/
    private HomeColumnModel cm;
    // 当前状态
    private int mCurrentStatus = ACTION_IDLE;
    // 目标状态
    private int mTargetStatus = ACTION_IDLE;
    private Activity context;

    public MainPageLiveVideoView(Activity context) {
        super(context);
        init(context);
    }

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

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

    private void init(Context context){
        this.context = (Activity) context;
        setOnClickListener(this);
        setFocusable(true);
    }

    /**
     * 创建视频播放器
     */
    private void createVideoView(){
        if(mVideoView == null){
            WLog.d(TAG, "createVideoView");
            mVideoView = new WasuLivePlayerView(context);
            mVideoView.setExcludeOption(MediaController.DISPLAY_PROMPT_EXIT_AD);
            mVideoView.addObserver(this);
            mVideoView.setAnchorView(this, this.context);
            MsgQueueModule.getInstance().addMsgHandler(MsgIdConstant.MSGID_APP_MIN + 1, this);
        }
    }

    /**
     * 设置播放器数据
     * @param bmData
     */

    AssetsDataModel assetsDataModel;
    public void initData(List<AssetsDataModel> bmData) {
        assetsDataModel = bmData.get(0);
        WLog.d(TAG,TAG + " initData");
        if (!TextUtils.isEmpty(assetsDataModel.getLayout())) {
            setVisibility(VISIBLE);
            requestFocus();
            if (LayoutCodeMap.PLAYER_WASU_LOOP.equals(assetsDataModel.getLayout())) {
                if (!TextUtils.isEmpty(assetsDataModel.getPicUrl())) {
                    setLiveVideoBackground(assetsDataModel.getPicUrl());
                }
                jsonUrl = assetsDataModel.getJsonUrl();
                if(this.hasFocus()){
                    startPlay();
                }
            } else {
                if (!TextUtils.isEmpty(assetsDataModel.getPicUrl())) {
                    setLiveVideoBackground(assetsDataModel.getPicUrl());
                    if(null == mVideoView) {
                        createVideoView();
                    }
                    mVideoView.setLoadingViewBackground(assetsDataModel.getPicUrl());
                }
            }
        } else {
            //layout为空对应下线轮播窗逻辑:隐藏轮播窗口
            setVisibility(GONE);
            try {
                finalize();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    }

    SimpleDraweeView poster;
    private void setLiveVideoBackground (String url) {
        View view = LayoutInflater.from(context).inflate(R.layout.liveposter, this);
        poster = (SimpleDraweeView) view.findViewById(R.id.poster);
        poster.setVisibility(VISIBLE);
        //轮播坑口像素尺寸615*390
        final int width = (int) getResources().getDimension(R.dimen.d_410dp);
        final int height = (int) getResources().getDimension(R.dimen.d_260dp);
        FrescoImageFetcherModule.getInstance().attachImageResize(url, poster, width, height);
    }

    /**
     * 点击播放器切换为全屏
     */
    @Override
    public void onClick(View v) {
        if (assetsDataModel == null || TextUtils.isEmpty(assetsDataModel.getLayout()) || TextUtils.isEmpty(assetsDataModel.getJsonUrl())) {
            return;
        }
        if (LayoutCodeMap.PLAYER_WASU_LOOP.equals(assetsDataModel.getLayout())) {
            if (mVideoView != null) {
                if (!mVideoView.isPlaying()) {
                    startPlay();
                }
                mVideoView.setVisibility(VISIBLE);
                mVideoView.toggleFullScreen();

                AppUtil.playEnter = "推荐"+"_1_5";
                WasuStatistics.getInstance().homeItemClick(1,"推荐","1_5","","推荐屏直播播放器");
            }
        } else {
            AppUtil.playEnter = "推荐" + "_1_5";
            WasuStatistics.getInstance().homeItemClick(1, "推荐", "1_5", "", "推荐屏轮播窗口");
            IntentMap.startIntent(context, null, assetsDataModel.getLayout(), assetsDataModel.getJsonUrl(), null);
        }
    }

    public boolean VideoViewIsFullScreen(){
        if(mVideoView != null){
            return  mVideoView.isFullScreen();
        }
        return false;
    }

    /**
     * 直播视频逻辑处理handler
     */
    Handler videoHandler =  new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case ACTION_PLAY:
                    /**创建播放器**/
                    createVideoView();
                    startPlay();
                    break;
                case ACTION_RESUME:
                    resumePlay();
                    break;
            }
            return false;
        }
    });

    /**
     * 播放器获得焦点
     */
    public void onFocused(){
        if(mVideoView!=null){
            if(mVideoView.isPlaying()){
                WLog.d(TAG, "VideoView isPlaying return!");
                return;
            }
            if(mVideoView.isPreparing()){
                WLog.d(TAG, "VideoView isPreparing!");
            }
            /**移除之前的任务，防止重复**/
            videoHandler.removeMessages(ACTION_RESUME);
            /**延时3秒钟播放视频**/
            videoHandler.sendEmptyMessageDelayed(ACTION_RESUME, delayedTime);
        }else{
            /**当播放器为空的时候回去创建播放器，一般会在第一次获得焦点时调用，不排除播放器在后台被回收掉了的时候也会调用**/
            /**移除之前的任务，防止重复**/
            videoHandler.removeMessages(ACTION_PLAY);
            /**延时3秒钟播放视频**/
            videoHandler.sendEmptyMessageDelayed(ACTION_PLAY, delayedTime);
        }
    }

    /**
     * 失去焦点时取消之前发送的MSG
     */
    public void onUnFocused(){
        videoHandler.removeMessages(ACTION_RESUME);
        videoHandler.removeMessages(ACTION_PLAY);
    }

    /**
     * 暂停视频播放，对外调用
     */
    public void pauseToPlay(){
        videoHandler.removeMessages(ACTION_RESUME);
        videoHandler.removeMessages(ACTION_PLAY);
        pausePlay();
    }

    /**
     * 开始播放视频,只提供给内部调用
     */
    private void startPlay(){
        if(mVideoView==null || mVideoView.isPlaying()){
            WLog.e(TAG, "start to play return");
            return;
        }
        if(jsonUrl == null || TextUtils.isEmpty(jsonUrl)){
            WLog.e(TAG, "MainPageLiveVideoView jsonUrl is null");
            return;
        }
        if (!isCover()) {
            mVideoView.play(jsonUrl, 0);
            Log.d(TAG, "Live播放成功");
            mVideoView.start();
        }
        mVideoView.setVisibility(VISIBLE);
    }

    /**
     * 暂停播放
     */
    private void pausePlay(){
        if(mVideoView != null) {
            WLog.d(TAG, "pausePlay");
            mVideoView.pause();
            mVideoView.setVisibility(INVISIBLE);
        }
    }

    public void stopPlay(){
        if(mVideoView != null) {
            mVideoView.stopPlayback();
            mVideoView.setVisibility(INVISIBLE);
            WLog.d(TAG, "stopPlay");
        }
    }

    /**
     * 恢复播放
     */
    public void resumePlay(){
        if(isCover()){ //如果部分遮住了就不恢复视频播放
            return;
        }
        if(mVideoView != null && mVideoView.getCurPlayUrl() == null){
            /**播放器第一次没有成功加载到数据就暂停了播放后再次获得焦点后无法恢复播放**/
            mVideoView.setVisibility(VISIBLE);
            startPlay();
            return;
        }
        if(mVideoView != null && mVideoView.getCurPlayUrl() != null) {
            WLog.d(TAG, "resumePlay");
            mVideoView.setVisibility(VISIBLE);
            mVideoView.resume(mVideoView.getCurPlayUrl());
        }else{
            WLog.d(TAG, "resumePlay return");
        }
    }

    /**
     * 控件可见性的改变监听
     * @param visibility
     */
    @Override
    protected void onWindowVisibilityChanged(int visibility) {
        if(visibility == INVISIBLE){ //被覆盖就暂停播放
            pausePlay();
        }
    }

    /**
     * 监听首页轮播播放器播放成功
     */
    public interface LiveVideoViewOnStartListener{
        void onResume();
    }

    private LiveVideoViewOnStartListener onStartListener;

    public void setOnStartListener(LiveVideoViewOnStartListener onStartListener){
        this.onStartListener = onStartListener;
    }

    @Override
    public void onStart(MediaPlayer mediaPlayer) {

    }


    @Override
    public void onPreparing(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onPrepareComplete(MediaPlayer mediaPlayer) {
    }

    @Override
    public void onSeeking(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onSeekComplete(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onProgress(int i, int i1, int i2) {

    }

    @Override
    public void onPause(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onResume(MediaPlayer mediaPlayer) {
        if(onStartListener!=null){
            onStartListener.onResume();
        }
    }

    @Override
    public void onStop(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {

    }

    @Override
    public void onError(MediaPlayer mediaPlayer, int i, int i1) {

    }

    @Override
    public void onInfo(MediaPlayer mediaPlayer, int i, int i1) {

    }

    @Override
    public void onStatusChanged(MediaPlayer mediaPlayer, int i) {

    }

    @Override
    public void onAdStatusChanged(int i, int i1) {

    }

    @Override
    public void onWasuError(int i, String s) {

    }

    @Override
    public void onWasuPlayLimit(int i, String s) {

    }

    @Override
    public boolean handleMsg(int i, int i1, String s, Object o) {
        return true;
    }

    /**
     * 检测控件是否被全部显示出来了！
     * @return
     */
    public boolean isCover() {
        boolean cover = false;
        Rect rect = new Rect();
        cover = getGlobalVisibleRect(rect);
        if (cover) {
            if (rect.width() >= getMeasuredWidth() && rect.height() >= getMeasuredHeight()) {
                return !cover;
            }
        }
        return true;
    }
    @Override
    public void finalize() throws Throwable {
        super.finalize();
        if (mVideoView != null){
            mVideoView.removeObserver(this);
            mVideoView.removeAllViews();
            mVideoView = null;
        }
    }

}
