package com.pixelized.desktop.lwa.ui.composable.character.diminished

import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import com.pixelized.desktop.lwa.repository.network.NetworkRepository
import com.pixelized.shared.lwa.protocol.websocket.CharacterSheetEvent

class CharacterSheetDiminishedDialogViewModel(
    private val networkRepository: NetworkRepository,
    private val factory: CharacterSheetDiminishedDialogFactory,
) : ViewModel() {

    private val _diminishedDialog = mutableStateOf<CharacterSheetDiminishedDialogUio?>(null)
    val diminishedDialog: State<CharacterSheetDiminishedDialogUio?> get() = _diminishedDialog

    suspend fun showDiminishedDialog(
        characterSheetId: String?,
    ) {
        _diminishedDialog.value = factory.convertToDialogUio(
            characterSheetId = characterSheetId,
        )
    }

    fun hideDiminishedDialog() {
        _diminishedDialog.value = null
    }

    suspend fun changeDiminished(
        dialog: CharacterSheetDiminishedDialogUio,
    ) {
        val diminished = dialog.value().text.toIntOrNull() ?: 0
        networkRepository.share(
            message = CharacterSheetEvent.UpdateDiminished(
                timestamp = System.currentTimeMillis(),
                characterSheetId = dialog.characterSheetId,
                diminished = diminished,
            )
        )
    }
}