package com.swago.baseswago.baseroom

import com.swago.baseswago.util.IMUtil
import com.swago.baseswago.util.LogUtil
import com.swago.baseswago.util.UserInfo
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMManager

/**
 *@date 2021/10/4 09:22
 *description:
 */
object SwagoRoomManager : RoomStateManager(){

    fun createRoom(iRoomInfo: IRoomInfo){
        if (this.iRoomInfo!=null){
            this.iRoomInfo = null
        }
        startLiveRoom(iRoomInfo)
        joinRoomIMGroup(iRoomInfo)
    }

    fun joinRoom(iRoomInfo: IRoomInfo){
        joinedRoom(iRoomInfo)
        joinRoomIMGroup(iRoomInfo)
    }

    private fun joinRoomIMGroup(iRoomInfo: IRoomInfo) {
        val roomGroupId = iRoomInfo.getRoomGroupId()
        val joinRoomIMGroupTask = {
            V2TIMManager.getInstance().joinGroup(roomGroupId,"",object:V2TIMCallback{
                override fun onSuccess() {
                    LogUtil.d("加群成功--群id$roomGroupId")
                    if (roomGroupId!=this@SwagoRoomManager.iRoomInfo?.getRoomGroupId()){
                        V2TIMManager.getInstance().quitGroup(roomGroupId,object:V2TIMCallback{
                            override fun onSuccess() {
                                LogUtil.d("退群成功--群id$roomGroupId")
                            }

                            override fun onError(code: Int, desc: String?) {
                                LogUtil.d("退群失败--$code")
                            }
                        })
                    }else{
                        iRoomActiveListeners.forEach {
                            it.joinIMGroupFail(iRoomInfo)
                        }
                    }
                }

                override fun onError(code: Int, desc: String?) {
                    iRoomActiveListeners.forEach {
                        it.joinIMGroupFail(iRoomInfo)
                    }
                }

            })
        }

        if (IMUtil.checkIsLogin()){
            joinRoomIMGroupTask.invoke()
        }else{
            UserInfo.getLoginModel()?.let {
                V2TIMManager.getInstance().login(it.user_account, it.user_sig, object : V2TIMCallback {
                    override fun onSuccess() {
                        joinRoomIMGroupTask.invoke()
                    }

                    override fun onError(code: Int, desc: String?) {
                        iRoomActiveListeners.forEach {
                            it.joinIMGroupFail(iRoomInfo)
                        }
                    }

                })
            }
        }
    }


    fun closeRoom(){
        if (iRoomInfo!=null&&roleType == RoleType.user){
            val roomGroupId = iRoomInfo!!.getRoomGroupId()
            V2TIMManager.getInstance().quitGroup(roomGroupId,object:V2TIMCallback{
                override fun onSuccess() {}

                override fun onError(code: Int, desc: String?) {}

            })
        }
        closedRoom()
    }

}