package space.nstart.pcp.complan.apl

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import space.nstart.pcp.complan.types.ObservationParametersDebugFileDTO
import java.nio.file.Files
import java.nio.file.Path
import java.util.UUID

private val DEFAULT_OBSERVATION_PARAMETERS_OUTPUT_DIR =
    "/home/dsolovyov/ws/264/pcp/services/pcp-dynamic-plan-service/obsParams"

@Service
class ObservationParametersDebugFileWriter(
    private val objectMapper: ObjectMapper,

    @param:Value("\${complex-plan.observation-parameters.debug-output-dir:/home/dsolovyov/ws/264/pcp/services/pcp-dynamic-plan-service/obsParams}")
    private val outputDir: String = DEFAULT_OBSERVATION_PARAMETERS_OUTPUT_DIR
) {
    fun write(artifact: ObservationParametersDebugFileDTO): Path {
        val directory = Path.of(outputDir).toAbsolutePath().normalize()
        Files.createDirectories(directory)

        val file = filePathFor(artifact.requestId)
        objectMapper.writerWithDefaultPrettyPrinter().writeValue(file.toFile(), artifact)
        return file
    }

    fun read(file: Path): ObservationParametersDebugFileDTO =
        objectMapper.readValue(file.toFile())

    fun readByRequestId(requestId: UUID): ObservationParametersDebugFileDTO =
        read(filePathFor(requestId))

    fun filePathFor(requestId: UUID): Path {
        val directory = Path.of(outputDir).toAbsolutePath().normalize()
        return directory.resolve("observation-parameters-$requestId.json")
    }
}
