package com.adealink.weparty.room.member.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.livedata.ExtLiveData
import com.adealink.frame.mvvm.livedata.ExtMutableLiveData
import com.adealink.frame.mvvm.livedata.OnceMutableLiveData
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.module.profile.data.UserInfo
import com.adealink.weparty.module.room.viewmodel.IRoomMemberViewModel
import com.adealink.weparty.room.sdk.listener.IMemberListener
import com.adealink.weparty.room.sdk.service.roomService
import kotlinx.coroutines.launch

class RoomMemberViewModel : BaseViewModel(),
    IRoomMemberViewModel,
    IMemberListener {

    override val onlineMemberCountLD: LiveData<Long> = MutableLiveData()
    override val audienceJoinedLD: ExtLiveData<UserInfo> = ExtMutableLiveData()

    private val memberController by lazy { roomService.memberController }

    init {
        memberController.addListener(this)
    }

    override fun getRoomMemberInfo(uid: String): LiveData<Rlt<UserInfo>> {
        val liveData = OnceMutableLiveData<Rlt<UserInfo>>()
        viewModelScope.launch {
            liveData.send(memberController.getMemberInfoWithRetry(uid))
        }
        return liveData
    }

    override fun getRoomMembersInfo(uidSet: Set<String>): LiveData<Rlt<Map<String, UserInfo>>> {
        val liveData = OnceMutableLiveData<Rlt<Map<String, UserInfo>>>()
        viewModelScope.launch {
            liveData.send(memberController.getMembersInfo(uidSet))
        }
        return liveData
    }


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

    override fun onMemberCountChanged(count: Long) {
        onlineMemberCountLD.send(count)
    }

    override fun onAudienceJoined(userInfo: UserInfo) {
        audienceJoinedLD.send(userInfo)
    }
}