package com.swago.baseswago.agora

import android.content.Context
import android.util.Log
import android.widget.FrameLayout
import com.swago.baseswago.R
import com.swago.baseswago.baseroom.RoleType
import com.swago.baseswago.constant.UrlConstant
import com.swago.baseswago.util.AppContext
import com.swago.baseswago.util.LogUtil
import io.agora.rtc.Constants.*
import io.agora.rtc.IRtcEngineEventHandler
import io.agora.rtc.RtcEngine
import io.agora.rtc.models.ClientRoleOptions
import io.agora.rtc.video.VideoCanvas
import io.agora.rtc.video.VideoEncoderConfiguration
import java.lang.Exception

/**
 *@date 2021/10/6 11:16
 *description:
 */
object AgoraManager {

    private var mRtcEngine: RtcEngine? = null
    private var userType = -1
    private var iSwagoIRtcEngineEventHandler:ISwagoIRtcEngineEventHandler? = null

    fun initializeEngine(context: Context,iRtcEngineEventHandler: ISwagoIRtcEngineEventHandler) {
        try {
            this.iSwagoIRtcEngineEventHandler = iRtcEngineEventHandler
            mRtcEngine = RtcEngine.create(
                context,
                UrlConstant.agoraId,
                object : IRtcEngineEventHandler() {

                    override fun onUserOffline(uid: Int, reason: Int) {
                        super.onUserOffline(uid, reason)
                    }

                    override fun onError(err: Int) {
                        super.onError(err)
                        LogUtil.d("声网错误码-$err")
                    }

                    override fun onFirstLocalAudioFramePublished(elapsed: Int) {
                        super.onFirstLocalAudioFramePublished(elapsed)
                        LogUtil.d("首帧推出")
                    }

                    override fun onFirstRemoteVideoDecoded(
                        uid: Int,
                        width: Int,
                        height: Int,
                        elapsed: Int
                    ) {
                        super.onFirstRemoteVideoDecoded(uid, width, height, elapsed)
                        LogUtil.d("首帧解码")
                    }

                    override fun onFirstRemoteVideoFrame(
                        uid: Int,
                        width: Int,
                        height: Int,
                        elapsed: Int
                    ) {
                        super.onFirstRemoteVideoFrame(uid, width, height, elapsed)
                        LogUtil.d("首帧视频")
                        iSwagoIRtcEngineEventHandler?.onFirstRemoteVideoDecoded(uid, width, height, elapsed)
                    }

                    override fun onConnectionStateChanged(state: Int, reason: Int) {
                        super.onConnectionStateChanged(state, reason)
                        iSwagoIRtcEngineEventHandler?.onConnectionStateChanged(state, reason)
                    }

                })
            setChannelProfile()
        } catch (e: Exception) {
            LogUtil.d(Log.getStackTraceString(e))
            throw RuntimeException(
                "NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(
                    e
                )
            )
        }
    }


    private fun setChannelProfile() {
        mRtcEngine?.setChannelProfile(CHANNEL_PROFILE_LIVE_BROADCASTING)
    }


    fun setClientRole(userType: Int) {
        mRtcEngine?.enableVideo()
        this.userType = userType
        if (userType == RoleType.anchor) {
            mRtcEngine?.setClientRole(CLIENT_ROLE_BROADCASTER)
        } else if (userType == RoleType.user) {
            val clientRoleOptions = ClientRoleOptions()
            clientRoleOptions.audienceLatencyLevel = AUDIENCE_LATENCY_LEVEL_LOW_LATENCY
            mRtcEngine?.setClientRole(CLIENT_ROLE_AUDIENCE, clientRoleOptions)
        }
    }

    /**
     * 主播设置预览画面
     */
    fun setupLocalVideo(context: Context, mLocalContainer: FrameLayout) {
        mRtcEngine?.startPreview()
        val mLocalView = RtcEngine.CreateRendererView(context)
        mLocalView.setZOrderMediaOverlay(true)
        mLocalContainer.addView(mLocalView)
        mRtcEngine?.setupLocalVideo(VideoCanvas(mLocalView, VideoCanvas.RENDER_MODE_HIDDEN, 0))
    }


    /**
     * 观众拉取远端主播画面
     */
    fun setupRemoteVideo(context: Context, anchorId: Int, mLocalContainer: FrameLayout) {
        val remoteView = RtcEngine.CreateRendererView(context)
        mLocalContainer.addView(remoteView)
        val result = mRtcEngine?.setupRemoteVideo(
            VideoCanvas(
                remoteView,
                VideoCanvas.RENDER_MODE_HIDDEN,
                anchorId
            )
        )
        LogUtil.d("$result")
    }

    fun joinChannel(channelName: String, userId: Int, token: String = "", option: String = "") {
        val result = mRtcEngine?.joinChannel(token, channelName, option, userId)
        Log.d("result", "$result")
    }


    /**
     * 观众切换房间
     */
    fun changeRoom(anchorId: Int, frameLayout: FrameLayout?) {
        mRtcEngine?.setupRemoteVideo(VideoCanvas(null, VideoCanvas.RENDER_MODE_HIDDEN, anchorId))
        frameLayout?.removeAllViews()
        mRtcEngine?.leaveChannel()
    }

    fun leaveChannel() {
        mRtcEngine?.leaveChannel()
    }

    /**
     * 关闭房间
     */
    fun closedRoom() {
        if (userType == RoleType.anchor) {
            mRtcEngine?.stopPreview()
        }
        mRtcEngine?.disableVideo()
        mRtcEngine?.leaveChannel()
        RtcEngine.destroy()
    }

    /**
     * 未开播的情况下离开直播间
     */
    fun closePrepareRoom() {
        if (userType == RoleType.anchor) {
            mRtcEngine?.stopPreview()
        }
        mRtcEngine?.disableVideo()
        RtcEngine.destroy()
    }


    fun setVideoConfiguration(
        vd: VideoEncoderConfiguration.VideoDimensions = VideoEncoderConfiguration.VD_640x480,
        fps: VideoEncoderConfiguration.FRAME_RATE = VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15
    ) {
        mRtcEngine?.setVideoEncoderConfiguration(
            VideoEncoderConfiguration(
                vd, fps,
                VideoEncoderConfiguration.STANDARD_BITRATE,
                VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT
            )
        )
    }

    /**
     * 切换摄像头
     */
    fun changeCameraOrientation() {
        mRtcEngine?.switchCamera()
    }

    /**
     * 设置镜像
     */
    var isMirror = true
    fun setMirror(userId: Int) {
        if (isMirror) {
            mRtcEngine?.setRemoteRenderMode(userId, RENDER_MODE_HIDDEN, VIDEO_MIRROR_MODE_DISABLED)
        } else {
            mRtcEngine?.setRemoteRenderMode(userId, RENDER_MODE_HIDDEN, VIDEO_MIRROR_MODE_ENABLED)
        }
        isMirror = !isMirror
    }

    /**
     * 打开或者关闭本地音频流
     */
    private var mMuted = false
    fun setMute(){
        mMuted = !mMuted
        mRtcEngine?.muteLocalAudioStream(mMuted)
    }
}