package com.adealink.weparty.gift.viewmodel

import androidx.lifecycle.LiveData
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.App
import com.adealink.weparty.gift.data.SendGiftReq
import com.adealink.weparty.gift.datasource.remote.GiftHttpService
import com.adealink.weparty.gift.manager.giftManager
import com.adealink.weparty.module.gift.data.GiftInfo
import com.adealink.weparty.module.gift.listener.IGiftListener
import com.adealink.weparty.module.gift.viewmodel.IGiftViewModel
import com.adealink.weparty.module.room.RoomModule
import kotlinx.coroutines.launch

class GiftViewModel : BaseViewModel(), IGiftViewModel, IGiftListener {
    override val sendGiftRltLD: ExtLiveData<Rlt<Any>> = ExtMutableLiveData()
    override val giftsLD: ExtLiveData<List<GiftInfo>> = ExtMutableLiveData()

    private val giftHttpService by lazy {
        App.instance.networkService.getHttpService(GiftHttpService::class.java)
    }

    init {
        giftManager.addListener(this)
    }

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

    override fun getGifts(roomId: String, forceNet: Boolean) {
        viewModelScope.launch {
            giftManager.getGifts(roomId, forceNet)
        }
    }

    override fun sendGift(toUids: Set<String>, gift: GiftInfo, count: Int, useCoinIfLess: Boolean): LiveData<Rlt<Any>> {
        val liveData = OnceMutableLiveData<Rlt<Any>>()
        viewModelScope.launch {
            val roomId = RoomModule.getJoinedRoomId() ?: return@launch
            val rlt = giftHttpService.sendGift(
                SendGiftReq(
                    roomId,
                    gift.id,
                    toUids.toList(),
                    count,
                    useCoinIfLess
                )
            )
            liveData.send(rlt)
        }
        return liveData
    }

    override fun onGifts(gifts: List<GiftInfo>) {
        giftsLD.send(gifts)
    }

}