package com.bokecc.livemodule.live.video;

import android.app.Activity;
import android.content.Context;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bokecc.dwlivedemo.R;
import com.bokecc.livemodule.live.DWLiveCoreHandler;
import com.bokecc.livemodule.live.DWLiveVideoListener;
import com.bokecc.livemodule.utils.ImageLoader;
import com.bokecc.livemodule.utils.NetworkUtils;
import com.bokecc.livemodule.view.CustomToast;
import com.bokecc.livemodule.view.VideoLoadingView;
import com.bokecc.sdk.mobile.live.DWLive;
import com.bokecc.sdk.mobile.live.Exception.DWLiveException;
import com.bokecc.sdk.mobile.live.player.LiveRtmpPlayerCallBack;
import com.bokecc.sdk.mobile.live.stream.live.rtc.HDMediaView;
import com.bokecc.stream.ali.CCBasePlayer;

/**
 * CC 直播视频展示控件
 * 说明: 此处存在Surface动态初始化失败的问题，后续考虑怎么优化
 */
public class LiveVideoView extends RelativeLayout implements DWLiveVideoListener {
    private final String TAG = LiveVideoView.class.getSimpleName();

    private Context mContext;
    /**
     * 视频显示容器
     */
    private FrameLayout mVideoContainer;
    /**
     * 视频加载进度
     */
    private VideoLoadingView mVideoProgressBar;
    /**
     * 音频模式界面
     */
    private View audioModeRoot;
    private ImageView audioUndulate;

    private HDMediaView hdMediaView;

    private boolean videoAdded = false;

    private boolean verticalMode = false;

    /**
     * 是否在开课状态
     */
    private boolean isStreamStart = true;

    public LiveVideoView(Context context) {
        super(context);
        initViews(context);
    }

    public LiveVideoView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initViews(context);
    }

    public LiveVideoView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initViews(context);
    }

    public void initViews(Context context) {
        this.mContext = context;
        inflateViews();
        initPlayer();
    }

    /**
     * 初始化视图对象
     */
    private void inflateViews() {
        View mRootView = LayoutInflater.from(mContext).inflate(R.layout.live_video_view, null);
        mVideoContainer = mRootView.findViewById(R.id.live_video_container);
        mVideoProgressBar = mRootView.findViewById(R.id.video_progressBar);
        audioModeRoot = mRootView.findViewById(R.id.audio_root);
        audioUndulate = mRootView.findViewById(R.id.iv_audio_undulate);
        addView(mRootView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
    }

    /**
     * 初始化播放器
     */
    private void initPlayer() {
        DWLive.getInstance().setPublishStreamListener(event);
        DWLiveCoreHandler dwLiveCoreHandler = DWLiveCoreHandler.getInstance();
        if (dwLiveCoreHandler != null) {
            dwLiveCoreHandler.setDwLiveVideoListener(this);
        }
    }

    /**
     * 视频播放控件进入连麦模式
     *
     * @param isVideoRtc : 是否显示连麦
     */
    public void enterRtcMode(boolean isVideoRtc) {
        if (isVideoRtc){
            setVisibility(GONE);
        }else {
            setVisibility(VISIBLE);
        }
    }

    /**
     * 视频播放控件退出连麦模式
     */
    public void exitRtcMode() {
        //如果是7不走
        setVisibility(VISIBLE);
    }

    /**
     * 开始播放
     */
    public void start() {
        if (!NetworkUtils.isNetworkAvailable(mContext)) {
            Log.e(TAG,"LiveVideoView:Network UnAvailable!");
            return;
        }
        if (!DWLiveCoreHandler.getInstance().isRtcing()) {
            // 启动直播播放器
            DWLiveCoreHandler.getInstance().start(mContext);
            if (mVideoProgressBar != null) {
                mVideoProgressBar.setVisibility(VISIBLE);
            }
        }
    }

    /**
     * 停止播放
     */
    public void stop() {
        if (!DWLiveCoreHandler.getInstance().isRtcing()) {
            DWLiveCoreHandler dwLiveCoreHandler = DWLiveCoreHandler.getInstance();
            if (dwLiveCoreHandler != null) {
                dwLiveCoreHandler.stop();
            }
        }
    }

    /**
     * 释放播放器
     */
    public void destroy() {
        DWLiveCoreHandler dwLiveCoreHandler = DWLiveCoreHandler.getInstance();
        if (dwLiveCoreHandler != null) {
            dwLiveCoreHandler.destroy();
        }
    }

    /**
     * 切换音视频模式布局
     *
     * @param playMode DWLive.PlayMode
     */
    private void changeModeLayout(DWLive.LivePlayMode playMode) {
        if (playMode == DWLive.LivePlayMode.PLAY_MODE_TYEP_AUDIO) {
            audioModeRoot.setVisibility(VISIBLE);
//            ImageLoader.loadGifIntoImageView(mContext, R.drawable.gif_audio_undulate,audioUndulate);
        } else {
            audioModeRoot.setVisibility(GONE);
        }
    }

    /**
     * 设置防录屏
     * 该方法需要在Activity的OnCreate方法里调用
     *
     * @param activity activity
     */
    public void setAntiRecordScreen(Activity activity) {
        DWLive.getInstance().setAntiRecordScreen(activity);
    }


    private final LiveRtmpPlayerCallBack event = new LiveRtmpPlayerCallBack() {
        @Override
        public void onError(CCBasePlayer.CCPlayerError error, DWLiveException exception) {
            mVideoProgressBar.setVisibility(GONE);
            CustomToast.showToast(mContext, exception.getMessage(), Toast.LENGTH_SHORT);
            String msg = exception.getMessage();
            if (error == CCBasePlayer.CCPlayerError.URLINVALID) {
                // 无网或者无流异常
                msg = "网络异常，请刷新重试";
            } else if (error ==  CCBasePlayer.CCPlayerError.TIMEOUT) {
                msg = "请求超时，请刷新重试";
            } else {
                msg = "播放异常，请刷新重试";
            }
            DWLiveCoreHandler dwLiveCoreHandler = DWLiveCoreHandler.getInstance();
            if (dwLiveCoreHandler != null) {
                dwLiveCoreHandler.showError(msg);
            }
        }

        @Override
        public void onPlayStateChange(final CCBasePlayer.CCPlayerStatus state) {
            post(new Runnable() {
                @Override
                public void run() {
                    if (state == CCBasePlayer.CCPlayerStatus.PLAYING){
                        mVideoProgressBar.setVisibility(GONE);
                    }else if (state == CCBasePlayer.CCPlayerStatus.BUFFERRED){
                        mVideoProgressBar.setVisibility(GONE);
                    }else if (state == CCBasePlayer.CCPlayerStatus.BUFFERRING){
                        mVideoProgressBar.setVisibility(VISIBLE);
                    }
                }
            });
        }


        @Override
        public void onBufferSpeed(float speed) {
            if (mVideoProgressBar != null) {
                mVideoProgressBar.setSpeed(speed);
            }
        }

        @Override
        public void onVideoSizeChanged(int width, int height) {
            super.onVideoSizeChanged(width, height);
            if (verticalMode&&videoAdded&&hdMediaView!=null){
                videoAdded = false;
                FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) hdMediaView.getLayoutParams();
                WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
                Display display = wm.getDefaultDisplay();
                Point size = new Point();
                display.getSize(size);
                int swidth = size.x;
                int sheight = getScreenHeight(mContext);
                int outputWidth = width*sheight/height;
                layoutParams.width = outputWidth;
                layoutParams.height = sheight;
                hdMediaView.setTranslationX(-(outputWidth-swidth)/2);
                hdMediaView.setLayoutParams(layoutParams);

            }
        }
    };

    public static int getScreenHeight(Context context) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        ((Activity)context).getWindowManager().getDefaultDisplay().getRealMetrics(displayMetrics);
        return  displayMetrics.heightPixels;
    }

    //------------------------------------- SDK 回调相关 ---------------------------------------
    @Override
    public void onStreamEnd(final boolean isNormal) {
        post(new Runnable() {
            @Override
            public void run() {
                isStreamStart = false;
                mVideoProgressBar.setVisibility(View.GONE);

            }
        });
    }

    @Override
    public void onStreamStart() {
        isStreamStart = true;
    }


    /**
     * 播放状态
     *
     * @param status : 包括PLAYING, PREPARING共2种状态
     */
    @Override
    public void onLiveStatus(final DWLive.PlayStatus status) {
        post(new Runnable() {
            @Override
            public void run() {
                switch (status) {
                    case PLAYING:
                        // 直播正在播放
                        mVideoProgressBar.setVisibility(VISIBLE);
                        break;
                    case PREPARING:
                        // 直播未开始
                        mVideoProgressBar.setVisibility(GONE);
                        break;
                    default:
                        break;
                }
            }
        });
    }

    /**
     * 禁播
     *
     * @param reason : 禁播原因
     */
    @Override
    public void onBanStream(String reason) {
        post(new Runnable() {
            @Override
            public void run() {
                // 播放器停止播放
                DWLive.getInstance().pause();
                // 隐藏加载控件
                if (mVideoProgressBar != null) {
                    mVideoProgressBar.setVisibility(GONE);
                }
            }
        });
    }

    /**
     * 解禁
     */
    @Override
    public void onUnbanStream() {
        DWLiveCoreHandler dwLiveCoreHandler = DWLiveCoreHandler.getInstance();
        if (dwLiveCoreHandler != null) {
            dwLiveCoreHandler.start(mContext);
        }
    }

    @Override
    public void onChangePlayMode(DWLive.LivePlayMode playMode) {
        changeModeLayout(playMode);
    }

    @Override
    public void onLiveMediaView(final HDMediaView hdMediaView) {
        this.hdMediaView = hdMediaView;
        setVisibility(VISIBLE);
        if (mVideoContainer!=null){
            mVideoContainer.removeAllViews();
            mVideoContainer.addView(hdMediaView);
            videoAdded = true;
        }
    }

    /**
     * 设置模式为竖屏直播
     */
    public void setVerticalMode(){
        this.verticalMode = true;
    }


}
