package com.yunbao.one.views;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import com.tencent.rtmp.ITXLivePushListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLivePushConfig;
import com.tencent.rtmp.TXLivePusher;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.yunbao.common.utils.DpUtil;
import com.yunbao.common.utils.L;
import com.yunbao.common.utils.ToastUtil;
import com.yunbao.one.R;


/**
 * 0/7.
 * 腾讯云直播推流
 */

// +———————————————————————————————————
// | Created by Yunbao
// +———————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +———————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +———————————————————————————————————
// | Date: 2022-03-22
// +———————————————————————————————————
public class ChatLivePushTxViewHolder extends AbsChatLivePushViewHolder implements ITXLivePushListener {

    private static final String TAG = "ChatLivePushTxViewHolder";
    private View mRoot;
    private TXCloudVideoView mTXCloudVideoView;
    private TXLivePusher mLivePusher;
    private TXLivePushConfig mLivePushConfig;
    private boolean mBig;
    private boolean mPushStarted;

    public ChatLivePushTxViewHolder(Context context, ViewGroup parentView) {
        super(context, parentView);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.view_live_push_tx;
    }

    @Override
    public void init() {
        super.init();
        mRoot = findViewById(R.id.root);
        mBig = true;
        mLivePusher = new TXLivePusher(mContext);
        mLivePushConfig = new TXLivePushConfig();
        mLivePushConfig.setVideoFPS(15);//视频帧率
        mLivePushConfig.setVideoEncodeGop(1);//GOP大小
        mLivePushConfig.setVideoBitrate(1200);
        mLivePushConfig.setVideoResolution(TXLiveConstants.VIDEO_RESOLUTION_TYPE_540_960);
        Bitmap bitmap = decodeResource(mContext.getResources(), R.mipmap.bg_live_tx_pause);
        mLivePushConfig.setPauseImg(bitmap);
        mLivePushConfig.setTouchFocus(false);//自动对焦
        mLivePushConfig.enableAEC(true);//消除回声
        mLivePusher.setConfig(mLivePushConfig);
        mLivePusher.setMirror(true);
        mLivePusher.setPushListener(this);
        mTXCloudVideoView = (TXCloudVideoView) findViewById(R.id.camera_preview);

    }



    @Override
    public void setBig(boolean big) {
        if (mRoot == null || mBig == big) {
            return;
        }
        mBig = big;
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) mRoot.getLayoutParams();
        if (big) {
            params.width = ViewGroup.LayoutParams.MATCH_PARENT;
            params.height = ViewGroup.LayoutParams.MATCH_PARENT;
            params.topMargin = 0;
            params.rightMargin = 0;
            params.gravity = Gravity.NO_GRAVITY;
        } else {
            params.width = DpUtil.dp2px(120);
            params.height = DpUtil.dp2px(160);
            params.topMargin = DpUtil.dp2px(35);
            params.rightMargin = DpUtil.dp2px(5);
            params.gravity = Gravity.RIGHT;
        }
        mRoot.requestLayout();
    }


    /**
     * 切换镜头
     */
    @Override
    public void toggleCamera() {
        if (mLivePusher != null) {
            if (mFlashOpen) {
                toggleFlash();
            }
            mLivePusher.switchCamera();
            mCameraFront = !mCameraFront;
            mLivePusher.setMirror(mCameraFront);
        }
    }

    /**
     * 关麦
     */
    @Override
    public void setMute(boolean mute) {
        if (mLivePusher != null) {
            mLivePusher.setMute(mute);
        }
    }

    /**
     * 打开关闭闪光灯
     */
    @Override
    public void toggleFlash() {
        if (mCameraFront) {
            ToastUtil.show(R.string.live_open_flash);
            return;
        }
        if (mLivePusher != null) {
            boolean open = !mFlashOpen;
            if (mLivePusher.turnOnFlashLight(open)) {
                mFlashOpen = open;
            }
        }
    }

    /**
     * 开始推流
     *
     * @param pushUrl   推流地址
     * @param pureVoice 是否是纯音频推流
     */
    @Override
    public void startPush(String pushUrl, boolean pureVoice) {
        //L.e("推拉流问题-- "+CommonAppConfig.getInstance().getUid()+" --> 开始推流---> "+pushUrl);
        if (mLivePusher != null) {
            if (pureVoice) {
                if (mLivePushConfig != null) {
                    mLivePushConfig.enablePureAudioPush(true);
                    mLivePusher.setConfig(mLivePushConfig);
                }
            } else {
                if (mLivePushConfig != null) {
                    mLivePushConfig.enablePureAudioPush(false);
                    mLivePusher.setConfig(mLivePushConfig);
                }
                if (mTXCloudVideoView != null) {
                    mLivePusher.startCameraPreview(mTXCloudVideoView);
                }
            }
            int i = mLivePusher.startPusher(pushUrl);
            if (i == -5) {
                L.e(TAG, "startRTMPPush: license 校验失败");
            }
            mPushStarted = true;
        }
    }

    public void startCameraPreview() {
        if (mTXCloudVideoView != null) {
            mLivePusher.startCameraPreview(mTXCloudVideoView);
        }
    }

    @Override
    public void stopPush() {
        try {
            if (mPushStarted) {
                mPushStarted = false;
                if (mLivePusher != null && mLivePusher.isPushing()) {
                    mLivePusher.stopBGM();
                    mLivePusher.stopPusher();
                    mLivePusher.stopCameraPreview(true);
                }
            }
        } catch (Exception e) {
            L.e("---e----" + e.toString());
        }

    }


    @Override
    public void onPause() {
        mPaused = true;
        if (mLivePusher != null) {
            mLivePusher.pauseBGM();
            mLivePusher.pausePusher();
        }
    }

    @Override
    public void onResume() {
        if (mPaused && mLivePusher != null) {
            mLivePusher.resumePusher();
            mLivePusher.resumeBGM();
        }
        mPaused = false;
    }


    @Override
    public void release() {
        try {
            if (mLivePusher != null) {
//                mLivePusher.stopBGM();
                mLivePusher.stopPusher();
                mLivePusher.stopScreenCapture();
                mLivePusher.stopCameraPreview(false);
                mLivePusher.setVideoProcessListener(null);
//                mLivePusher.setBGMNofify(null);
                mLivePusher.setPushListener(null);
            }
            mLivePusher = null;
            if (mLivePushConfig != null) {
                mLivePushConfig.setPauseImg(null);
            }
            mLivePushConfig = null;
        } catch (Exception e) {

        }
        super.release();
    }

    @Override
    public void onPushEvent(int e, Bundle bundle) {
        L.e(TAG, "--e--" + e);
        if (e == TXLiveConstants.PUSH_ERR_OPEN_CAMERA_FAIL) {
            ToastUtil.show(R.string.live_push_failed_1);

        } else if (e == TXLiveConstants.PUSH_ERR_OPEN_MIC_FAIL) {
            ToastUtil.show(R.string.live_push_failed_1);
        } else if (e == TXLiveConstants.PUSH_ERR_NET_DISCONNECT || e == TXLiveConstants.PUSH_ERR_INVALID_ADDRESS) {
            L.e(TAG, "网络断开，推流失败------>");
        } else if (e == TXLiveConstants.PUSH_EVT_FIRST_FRAME_AVAILABLE) {//预览成功
            L.e(TAG, "mStearm--->初始化完毕");
            if (mLivePushListener != null) {
                mLivePushListener.onPreviewStart();
            }
        } else if (e == TXLiveConstants.PUSH_EVT_PUSH_BEGIN) {//推流成功
            L.e(TAG, "mStearm--->推流成功");
            //L.e("推拉流问题-- "+CommonAppConfig.getInstance().getUid()+" --> 推流成功--->");
            if (mLivePushListener != null) {
                mLivePushListener.onPushStart();
            }
        }
    }

    @Override
    public void onNetStatus(Bundle bundle) {

    }

    private Bitmap decodeResource(Resources resources, int id) {
        TypedValue value = new TypedValue();
        resources.openRawResource(id, value);
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inTargetDensity = value.density;
        return BitmapFactory.decodeResource(resources, id, opts);
    }


}
