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

import com.adealink.frame.data.json.toJsonErrorNull
import com.adealink.frame.log.Log
import com.adealink.frame.mvvm.viewmodel.BaseViewModel
import com.adealink.weparty.module.gift.GiftModule
import com.adealink.weparty.module.room.chat.data.ClearMicNotificationContent
import com.adealink.weparty.module.room.chat.data.Notification
import com.adealink.weparty.module.room.chat.data.ROOM_MESSAGE_ENTER_ROOM
import com.adealink.weparty.module.room.chat.data.ROOM_MESSAGE_SEND_GIFT
import com.adealink.weparty.module.room.chat.data.SendGiftContent
import com.adealink.weparty.module.room.chat.data.SendGiftNotificationContent
import com.adealink.weparty.room.sdk.service.roomService
import io.trtc.tuikit.atomicxcore.api.barrage.Barrage
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch

class RoomGiftViewModel : BaseViewModel() {

    init {
        viewModelScope.launch {
            launch {
                roomService.messageController.notificationsFlow.map { notifications ->
                    notifications.mapNotNull { if (it.content is SendGiftNotificationContent) it else null }
                }.distinctUntilChanged().collect { notifications ->
                    notifySendGift(notifications)
                }
            }
        }
    }

    private fun notifySendGift(notifications: List<Notification>) {
        val roomId = roomService.joinController.getJoinedRoomId() ?: return
        notifications.mapNotNull {
            if (it.barrage.liveID == roomId) {
                it.content as? SendGiftNotificationContent
            } else {
                null
            }
        }.forEach { content ->
            addSendGiftMessage(content)
        }
    }

    private fun addSendGiftMessage(
        content: SendGiftNotificationContent
    ) {
        viewModelScope.launch {
            for (contentData in content.list) {
                for (receiver in contentData.receivers) {
                    val messageContent = SendGiftContent(
                        contentData.sender,
                        receiver,
                        contentData.quantity,
                        contentData.resId,
                        hashMapOf(
                            contentData.sender to contentData.getUserInfo(contentData.sender),
                            receiver to contentData.getUserInfo(receiver)
                        )
                    )
                    roomService.messageController.sendLocalMessage(
                        Barrage().apply {
                            businessID = ROOM_MESSAGE_SEND_GIFT
                            data = toJsonErrorNull(messageContent) ?: ""
                        }
                    )
                }
            }
        }
    }

}