package com.omixlab.lckcontrol.ui.chat

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import com.omixlab.lckcontrol.data.remote.ChatConnectionStatus
import com.omixlab.lckcontrol.data.remote.ChatMessage
import com.omixlab.lckcontrol.data.repository.ChatRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject

@HiltViewModel
class ChatViewModel @Inject constructor(
    savedStateHandle: SavedStateHandle,
    private val chatRepository: ChatRepository,
) : ViewModel() {

    val planId: String = savedStateHandle["planId"] ?: ""
    val service: String = savedStateHandle["service"] ?: ""
    val destinationId: String = savedStateHandle["destinationId"] ?: ""

    private val chatKey = "$planId:$service:$destinationId"

    val allMessages: StateFlow<Map<String, List<ChatMessage>>> = chatRepository.messages
    val allConnectionStatus: StateFlow<Map<String, ChatConnectionStatus>> = chatRepository.connectionStatus

    fun getChatKey(): String = chatKey

    fun init() {
        chatRepository.setActiveView(chatKey)
    }

    fun sendMessage(text: String) {
        if (text.isBlank()) return
        chatRepository.sendMessage(planId, destinationId, text)
    }

    override fun onCleared() {
        chatRepository.clearActiveView()
        super.onCleared()
    }
}
