package com.pixelized.server.lwa.server.rest.campaign

import com.pixelized.server.lwa.server.Engine
import com.pixelized.server.lwa.utils.extentions.exception
import com.pixelized.shared.lwa.model.campaign.CampaignJsonV2
import com.pixelized.shared.lwa.protocol.rest.APIResponse
import com.pixelized.shared.lwa.protocol.websocket.CampaignEvent
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.RoutingContext

fun Engine.putCampaignScene(): suspend RoutingContext.() -> Unit {
    return {
        try {
            // Get the scene json from the body of the request
            val form = call.receive<CampaignJsonV2.SceneJsonV2>()
            // convert the scene into the a usable data model.
            val scene = campaignJsonFactory.convertFromJson(json = form)
            // update the campaign.
            campaignService.setScene(
                scene = scene,
            )
            // API & WebSocket responses
            call.respond(
                message = APIResponse.success(),
            )
            webSocket.emit(
                value = CampaignEvent.SceneUpdated(
                    timestamp = System.currentTimeMillis(),
                    name = scene.name,
                )
            )
        } catch (exception: Exception) {
            call.exception(
                exception = exception
            )
        }
    }
}