package com.pixelized.server.lwa.server.rest.character

import com.pixelized.server.lwa.server.Engine
import com.pixelized.server.lwa.utils.extentions.active
import com.pixelized.server.lwa.utils.extentions.alterationId
import com.pixelized.server.lwa.utils.extentions.characterSheetId
import com.pixelized.server.lwa.utils.extentions.exception
import com.pixelized.shared.lwa.protocol.rest.APIResponse
import com.pixelized.shared.lwa.protocol.websocket.CharacterSheetEvent
import io.ktor.server.response.respond
import io.ktor.server.routing.RoutingContext

fun Engine.putCharacterAlteration(): suspend RoutingContext.() -> Unit {
    return {
        try {
            // get the query parameter
            val characterSheetId = call.queryParameters.characterSheetId
            val alterationId = call.queryParameters.alterationId
            val active = call.queryParameters.active
            // Update the character damage
            characterService.updateAlteration(
                characterSheetId = characterSheetId,
                alterationId = alterationId,
                active = active
            )
            // API & WebSocket responses.
            call.respond(
                message = APIResponse.success()
            )
            webSocket.emit(
                value = CharacterSheetEvent.UpdateAlteration(
                    timestamp = System.currentTimeMillis(),
                    characterSheetId = characterSheetId,
                    alterationId = alterationId,
                    active = active,
                )
            )
        } catch (exception: Exception) {
            call.exception(
                exception = exception
            )
        }
    }
}