package com.pixelized.desktop.lwa.ui.screen.admin.action

import com.pixelized.desktop.lwa.repository.campaign.CampaignRepository
import com.pixelized.desktop.lwa.repository.characterSheet.CharacterSheetRepository
import com.pixelized.desktop.lwa.repository.network.NetworkRepository
import com.pixelized.shared.lwa.protocol.websocket.GameAdminEvent
import com.pixelized.shared.lwa.protocol.websocket.GameMasterEvent

class GMActionUseCase(
    private val characterRepository: CharacterSheetRepository,
    private val networkRepository: NetworkRepository,
    private val campaignRepository: CampaignRepository,
) {
    suspend fun invalidateServerCache() {
        networkRepository.share(
            GameAdminEvent.ServerSynchronization(
                timestamp = System.currentTimeMillis(),
            )
        )
    }

    fun currentSceneTitle(): String = campaignRepository.campaignFlow().value.scene.name

    suspend fun updateSceneTitle(
        title: String,
    ) {
        campaignRepository.updateSceneTitle(
            title = title,
        )
    }

    suspend fun healPlayerParty() {
        campaignRepository.campaignFlow().value.characters.forEach { characterSheetId ->
            val sheet = characterRepository.characterDetail(
                characterSheetId = characterSheetId,
            ) ?: return@forEach

            val updated = sheet.copy(
                damage = 0,
                fatigue = 0,
                diminished = 0,
            )

            if (sheet != updated) {
                characterRepository.updateCharacter(
                    sheet = updated,
                    create = false,
                )
            }
        }
    }

    suspend fun toggleNpcVisibility() {
        networkRepository.share(
            GameMasterEvent.ToggleNpc(
                timestamp = System.currentTimeMillis(),
            )
        )
    }

    suspend fun togglePlayerVisibility() {
        networkRepository.share(
            GameMasterEvent.TogglePlayer(
                timestamp = System.currentTimeMillis(),
            )
        )
    }
}