package com.cr.viewmodel

import androidx.lifecycle.MutableLiveData
import com.cr.common.CrLiveManager
import com.cr.common.CrLiveStreamStateInfo
import com.cr.data.CrUtil
import com.cr.models.CompletionModel
import com.cr.models.ICompletion
import dji.v5.common.callback.CommonCallbacks
import dji.v5.common.error.IDJIError
import dji.v5.common.video.channel.VideoChannelState
import dji.v5.common.video.channel.VideoChannelType
import dji.v5.manager.datacenter.MediaDataCenter
import dji.v5.manager.datacenter.livestream.*
import dji.v5.manager.datacenter.livestream.settings.RtmpSettings
import dji.v5.manager.datacenter.video.VideoStreamManager
import dji.v5.manager.interfaces.ILiveStreamManager

/**
 * 操作系统：MAC系统
 * 创建者：王成
 * 创建日期：2023/9/11 17:25
 * 描述：直播模型
 */
class CrLiveStreamVM : CrViewModel(){
    // todo: 2023/9/12 直播视频流状态信息
    var streamStatusInfo = MutableLiveData<CrLiveStreamStateInfo>()

    // todo: 2023/9/12 错误信息
    var streamErrorInfo = MutableLiveData<IDJIError>()

    // todo: 2023/9/12 监听
    private var liveStreamStatusListener:LiveStreamStatusListener? = null

    // todo: 2023/9/12 视频直播管理器
    private val liveStreamManager:ILiveStreamManager = MediaDataCenter.getInstance().liveStreamManager

    /**
     * 初始化
     */
    init {
        streamStatusInfo.postValue(CrLiveStreamStateInfo(false))
        // todo: 2023/9/12 重置初始化赋值
        reset()
        // todo: 2023/9/12 初始化监听
        liveStreamStatusListener = object:LiveStreamStatusListener{
            // todo: 2023/9/12 状态监听
            override fun onLiveStreamStatusUpdate(status: LiveStreamStatus?) {
                status?.let {
                    streamStatusInfo.value?.isStreaming = status.isStreaming
                    streamStatusInfo.value?.fps = status.fps
                    streamStatusInfo.value?.vbps = status.vbps
                    streamStatusInfo.value?.rtt = status.rtt
                    streamStatusInfo.value?.packetLoss = status.packetLoss
                    streamStatusInfo.value?.packetCacheLength = status.packetCacheLen
                    // todo: 2023/9/14 获取视频流质量
                    var resolution = CrLiveManager.getInstance().getQualityToVideoResolution(getLiveStreamQuality())
                    streamStatusInfo.value?.videoWidth = resolution[0]
                    streamStatusInfo.value?.videoHeight = resolution[1]
                    refresh(streamStatusInfo)
                }
            }

            // todo: 2023/9/12 错误监听
            override fun onError(error: IDJIError?) {
                error?.let {
                    streamErrorInfo.postValue(it)
                }
            }
        }
    }

    /**
     * 重写reset方法
     */
    override fun reset() {
        streamStatusInfo.value?.let {
            it.isStreaming = false
            it.fps = 0
            it.vbps = 0
            it.packetLoss = 0
            it.packetCacheLength = 0
            it.rtt = 0
            refresh(streamStatusInfo)
        }
    }

    /**
     * 销毁后调用
     */
    override fun onCleared() {
        super.onCleared()
        removeStreamStatusListener()
    }

    /**
     * 添加直播流状态监听
     */
    fun addStreamStatusListener(){
        liveStreamManager.addLiveStreamStatusListener(liveStreamStatusListener)
    }

    /**
     * 移除直播流状态监听
     */
    fun removeStreamStatusListener(){
        liveStreamManager.removeLiveStreamStatusListener(liveStreamStatusListener)
    }

    /**
     * 设置直播管理器
     * @param liveStreamSettings LiveStreamSettings
     */
    private fun setLiveStreamSettings(liveStreamSettings:LiveStreamSettings){
        liveStreamManager.liveStreamSettings = liveStreamSettings
    }

    /**
     * 开始直播
     * @param callback ICompletion<String>
     */
    fun startStream(callback:ICompletion<String>?){
        liveStreamManager.startStream(object:CommonCallbacks.CompletionCallback{
            // todo: 2023/9/12 成功
            override fun onSuccess() {
                callback.let { it?.onCompletion(CompletionModel(true,"")) }
            }

            // todo: 2023/9/12 失败
            override fun onFailure(error: IDJIError) {
                callback.let { it?.onCompletion(CompletionModel(false,error.description())) }
            }

        })
    }

    /**
     * 停止直播
     * @param callback ICompletion<String>
     */
    fun stopStream(callback: ICompletion<String>?){
        liveStreamManager.stopStream(object:CommonCallbacks.CompletionCallback{
            // todo: 2023/9/12 成功
            override fun onSuccess() {
                callback.let { it?.onCompletion(CompletionModel(true,"")) }
            }

            // todo: 2023/9/12 失败
            override fun onFailure(error: IDJIError) {
                callback.let { it?.onCompletion(CompletionModel(false,error.description())) }
            }
        })
    }


    /**
     * 设置直播流
     */
    fun setRTMStreamSettings(rtmpURL:String){
        // todo: 2023/9/12 创建配置
        val liveStreamRtmpSettings = LiveStreamSettings.Builder()
            .setLiveStreamType(LiveStreamType.RTMP)
            .setRtmpSettings(RtmpSettings.Builder().setUrl(rtmpURL).build())
            .build()
        // todo: 2023/9/12 设置配置
        setLiveStreamSettings(liveStreamRtmpSettings)
    }

    /**
     * 设置直播视频通道
     * @param videoChannel VideoChannelType
     */
    fun setVideoChannel(videoChannel: VideoChannelType){
        liveStreamManager.videoChannelType = videoChannel
    }

    /**
     * 获取直播视频通道
     * @return VideoChannelType
     */
    fun getVideoChannel():VideoChannelType{
        return liveStreamManager.videoChannelType
    }

    /**
     * 设置直播视频质量
     * @param liveStreamQuality StreamQuality
     */
    fun setLiveStreamQuality(liveStreamQuality:StreamQuality){
        liveStreamManager.liveStreamQuality = liveStreamQuality
    }

    /**
     * 获取直播视频质量
     * @return StreamQuality
     */
    fun getLiveStreamQuality():StreamQuality{
        return liveStreamManager.liveStreamQuality
    }

    /**
     * 设置直播视频码率模式
     * @param bitRateMode LiveVideoBitrateMode
     */
    fun setLiveVideoBitRateMode(bitRateMode: LiveVideoBitrateMode){
        liveStreamManager.liveVideoBitrateMode = bitRateMode
    }

    /**
     * 获取直播视频码率模式
     * @return LiveVideoBitrateMode
     */
    fun getLiveVideoBitReteMode():LiveVideoBitrateMode{
        return liveStreamManager?.liveVideoBitrateMode
    }

    /**
     * 设置直播视频码率
     * @param bitrate Int
     */
    fun setLiveVideoBitRate(bitrate: Int) {
        liveStreamManager.liveVideoBitrate = bitrate
    }

    /**
     * 判断直播选择的视频通道是否开启
     * @return Boolean
     */
    fun channelTypeIsOpen():Boolean{
         return getChannelStatus(liveStreamManager.videoChannelType) == VideoChannelState.ON
    }

    /**
     * 获取通道状态
     * @param channel VideoChannelType
     * @return VideoChannelState
     */
    fun getChannelStatus(channel: VideoChannelType): VideoChannelState {
        return VideoStreamManager.getInstance().getAvailableVideoChannel(channel)
            ?.let { it.videoChannelStatus } ?: let { VideoChannelState.CLOSE }
    }
}