package com.adealink.weparty.room.gift.viewmodel

import androidx.lifecycle.MutableLiveData
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.commonui.recycleview.diffutil.BaseListItemData
import com.adealink.weparty.module.profile.ProfileModule
import com.adealink.weparty.module.profile.data.UserInfo
import com.adealink.weparty.room.gift.data.RoomGiftTargetUserItemData
import com.adealink.weparty.room.gift.data.RoomGiftUserItemData
import com.adealink.weparty.room.micseat.dispatcenter.getMicIndexName
import io.trtc.tuikit.atomicxcore.api.live.SeatInfo
import kotlinx.coroutines.launch

class RoomGiftPanelViewModel : BaseViewModel() {

    val userInfoListLD = MutableLiveData<List<BaseListItemData>>()

    fun setTargetUser(uid: String) {
        viewModelScope.launch {
            when (val rlt = ProfileModule.getUserInfoByUid(uid)) {
                is Rlt.Failed -> {
                    userInfoListLD.send(
                        listOf(
                            RoomGiftTargetUserItemData(UserInfo.emptyUserInfo(uid, ""))
                        )
                    )
                }

                is Rlt.Success -> {
                    userInfoListLD.send(
                        listOf(
                            RoomGiftTargetUserItemData(rlt.data)
                        )
                    )
                }
            }

        }
    }

    fun updateSeatUser(seatInfoList: List<Map.Entry<Int, SeatInfo>>) {
        viewModelScope.launch {
            val uids = seatInfoList.map { it.value.userInfo.userID }.toList()
            when (val rlt = ProfileModule.getUsersInfoByUid(uids.toSet())) {
                is Rlt.Failed -> {
                    val userInfos = mutableListOf<RoomGiftUserItemData>()
                    for (entry in seatInfoList) {
                        userInfos.add(
                            RoomGiftUserItemData(
                                UserInfo.emptyUserInfo(entry.value.userInfo.userID, ""),
                                getMicIndexName(entry.key)
                            )
                        )
                    }
                    userInfoListLD.send(userInfos)
                }

                is Rlt.Success -> {
                    val userInfos = mutableListOf<RoomGiftUserItemData>()
                    for (entry in seatInfoList) {
                        val uid = entry.value.userInfo.userID
                        userInfos.add(
                            RoomGiftUserItemData(
                                rlt.data[uid] ?: UserInfo.emptyUserInfo(uid, ""),
                                getMicIndexName(entry.key)
                            )
                        )
                    }
                    userInfoListLD.send(userInfos)
                }
            }

        }
    }

}