package com.adealink.weparty.room.chat.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.adealink.frame.base.Rlt
import com.adealink.frame.mvvm.livedata.ExtMutableLiveData
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.module.room.chat.data.Message
import com.adealink.weparty.module.room.viewmodel.IChatMessageViewModel
import com.adealink.weparty.room.sdk.listener.IMessageListener
import com.adealink.weparty.room.sdk.service.roomService
import io.trtc.tuikit.atomicxcore.api.barrage.Barrage
import kotlinx.coroutines.launch

/**
 */
class ChatMessageViewModel : BaseViewModel(), IChatMessageViewModel, IMessageListener {

    init {
        roomService.messageController.addListener(this)
        viewModelScope.launch {
            roomService.messageController.messagesFlow.collect {
                onMessageListChanged(it)
            }
            roomService.messageController
        }
    }

    val messagesLD: LiveData<List<Message>> = MutableLiveData()
    override fun onCleared() {
        super.onCleared()
        roomService.messageController.removeListener(this)
    }

    val sendTextMessageResultLD = ExtMutableLiveData<Rlt<Any>>()
    fun sendTextMessage(text: String) {
        viewModelScope.launch {
            val rlt = roomService.messageController.sendTextMessage(text)
            sendTextMessageResultLD.send(rlt)
        }
    }

    fun sendLocalMessage(barrage: Barrage) {
        viewModelScope.launch {
            roomService.messageController.sendLocalMessage(barrage)
        }
    }


    private fun onMessageListChanged(messages: List<Message>) {
        messagesLD.send(messages)
    }

}