package com.adealink.weparty.room.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.adealink.frame.coroutine.dispatcher.Dispatcher
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.frame.room.data.FlowStateInfo
import com.adealink.frame.room.data.LeaveRoomReason
import com.adealink.frame.room.data.RoomFlowData
import com.adealink.frame.room.data.RoomState
import com.adealink.weparty.module.room.viewmodel.IRoomFlowViewModel
import com.adealink.weparty.room.sdk.listener.IJoinListener
import com.adealink.weparty.room.sdk.service.roomService
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

class RoomFlowViewModel : BaseViewModel(), IRoomFlowViewModel, IJoinListener {

    private val joinController by lazy { roomService.joinController }

    override val roomStateLD: LiveData<RoomFlowData> = MutableLiveData()

    init {
        joinController.addListener(this)
        roomStateLD.send(
            RoomFlowData(
                joinController.getJoinRoomState(),
                joinController.getJoinFlowData()
            )
        )
    }

    override fun tryLeaveRoom(reason: LeaveRoomReason) {
        CoroutineScope(Dispatcher.UI).launch {
            joinController.leaveRoom(reason)
        }
    }

    override fun getJoiningRoomId(): String? {
        return joinController.joiningRoomId
    }

    override fun getJoinedRoomId(): String? {
        return joinController.getJoinedRoomId()
    }

    override fun getJoinRoomState(): RoomState {
        return joinController.getJoinRoomState()
    }

    override fun onCleared() {
        super.onCleared()
        joinController.removeListener(this)
    }

    override fun onRoomStateChanged(
        fromState: RoomState,
        toState: RoomState,
        flowStateInfo: FlowStateInfo,
    ) {
        roomStateLD.send(RoomFlowData(toState, flowStateInfo), false)
    }

//    override fun onChannelStateChanged(fromState: ChannelState, toState: ChannelState, flowStateInfo: FlowStateInfo) {
//        channelStateLD.send(Triple(fromState, toState, flowStateInfo), false)
//    }

}