package com.adealink.weparty.media

import com.adealink.frame.base.Rlt
import com.adealink.frame.log.Log
import com.adealink.frame.media.IMediaOperatorGet
import com.adealink.frame.media.MediaInfo
import com.adealink.frame.media.constant.TAG_MEDIA
import com.adealink.frame.media.data.RtcType

enum class MediaType(val type: Int) {
    UNKNOWN(0), //未知
    CHAT_ROOM(1), //语聊房
    CALL_1V1(2) //1v1通话
}

class MediaManager : IMediaManager {

    private val mediaOperatorGets = arrayListOf<IMediaOperatorGet>(
//        RoomModule,
//        CallModule
    )

    override suspend fun conflictHandle(mediaInfo: MediaInfo): Rlt<Any> {
        val currentMediaOperate = mediaOperatorGets.find { it.getMediaOperator().isMediaIn() }
        if (currentMediaOperate == null) {
            //当前没有正在运行的媒体,可以直接跳转目标媒体
            return Rlt.Success(Any())
        }
        val currentOperator = currentMediaOperate.getMediaOperator()
        //检查当前媒体支不支持同时运行
        val currentConfig = currentOperator.getConflictConfig()
        if (!currentConfig.sameTypeConflict && mediaInfo.mediaType == currentConfig.mediaInfo.mediaType) {
            return Rlt.Success(Any())
        }


        //跳转前需要用户确认
        val toMediaOperate = mediaOperatorGets.find { it.getMediaOperator().getConflictConfig().mediaInfo.mediaType == mediaInfo.mediaType }
        if (toMediaOperate == null) {
            Log.e(TAG_MEDIA, "${mediaInfo.mediaType} miss MediaOperator")
            throw IllegalStateException("${mediaInfo.mediaType} miss MediaOperator")
        }
        val toMediaOperator = toMediaOperate.getMediaOperator()
        val confirmRlt = toMediaOperator.confirmExitConflictMedia(currentConfig.mediaInfo, mediaInfo)
        if (confirmRlt is Rlt.Failed) {
            return confirmRlt
        }

        val leaveMediaRlt = currentOperator.leaveMedia()
        if (leaveMediaRlt is Rlt.Failed) {
            return leaveMediaRlt
        }

        return Rlt.Success(Any())
    }

    override fun getJoinedMediaRoomId(): Long? {
        val mediaGet = mediaOperatorGets.find { it.getMediaOperator()?.getJoinedRoomId() != null }
        return mediaGet?.getMediaOperator()?.getJoinedRoomId()
    }

    override suspend fun rejoinRoom() {
        val mediaGet = mediaOperatorGets.find { it.getMediaOperator()?.getJoinedRoomId() != null }
        mediaGet?.getMediaOperator()?.rejoinRoom()
    }

    override fun getSupportRtc(): Byte {
        return (RtcType.AGORA_RTC.type or RtcType.T_RTC.type).toByte()
    }

}