package com.adealink.weparty.im.session.viewmodel

import com.adealink.frame.mvvm.livedata.ExtMutableLiveData
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.im.data.isCurrentSession
import com.tencent.qcloud.tuikit.timcommon.bean.TUIMessageBean
import com.tencent.qcloud.tuikit.tuichat.TUIChatService
import com.tencent.qcloud.tuikit.tuichat.bean.ChatInfo
import com.tencent.qcloud.tuikit.tuichat.interfaces.C2CChatEventListener


class SessionViewModel : BaseViewModel() {

    private var chatInfo: ChatInfo? = null

    val onRecvNewMessageLD = ExtMutableLiveData<TUIMessageBean>()

    fun setChatInfo(chatInfo: ChatInfo?) {
        this@SessionViewModel.chatInfo = chatInfo
    }

    private val c2cEventListener = object : C2CChatEventListener() {
        override fun onRecvNewMessage(message: TUIMessageBean?) {
            message ?: return
            if (message.isCurrentSession(chatInfo)) {
                this@SessionViewModel.onRecvNewMessage(message)
            }
        }

        override fun onMessageChanged(messageBean: TUIMessageBean?, dataChangeType: Int) {
            super.onMessageChanged(messageBean, dataChangeType)
        }
    }

    private fun onRecvNewMessage(message: TUIMessageBean) {
        onRecvNewMessageLD.send(message)
    }

    init {
        TUIChatService.getInstance().addC2CChatEventListener(c2cEventListener)
    }

    override fun onCleared() {
        super.onCleared()
        TUIChatService.getInstance().removeC2CChatEventListener(c2cEventListener)
    }


}