package de.arxsilex.maptools.converter.desktop

import de.arxsilex.maptools.converter.core.ContentSelection
import de.arxsilex.maptools.converter.core.MapFormatVersion
import de.arxsilex.maptools.converter.core.PoiSchemaVersion
import de.arxsilex.maptools.converter.core.pbf.PbfHeaderReader
import java.nio.file.Files
import java.nio.file.Path
import java.util.Comparator
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue

class PackagedWorkerIntegrationTest {
    @Test
    fun `packaged Windows launcher waits for worker and produces a map`() {
        val inputValue = System.getenv("MAPTOOLS_PACKAGED_WORKER_SMOKE_INPUT") ?: return
        val resourcesValue = System.getenv("MAPTOOLS_PACKAGED_WORKER_RESOURCES") ?: return
        val input = Path.of(inputValue)
        val outputDirectory = Files.createTempDirectory("maptools-packaged-worker-test-")
        val output = outputDirectory.resolve("smoke.map")
        val previousResources = System.getProperty("compose.application.resources.dir")
        try {
            System.setProperty("compose.application.resources.dir", resourcesValue)
            val result = WorkerLauncher.mapsforge(
                input = input,
                mapOutput = output,
                poiOutput = null,
                bounds = requireNotNull(PbfHeaderReader.read(input).bounds),
                content = ContentSelection(),
                mapFormatVersion = MapFormatVersion.V5,
                poiSchemaVersion = PoiSchemaVersion.V4,
                preferDiskProcessor = true,
                temporaryDirectory = outputDirectory,
                logDirectory = outputDirectory,
            )

            assertEquals(Files.size(output), result.outputs[output])
            assertTrue(Files.size(output) > 0L)
        } finally {
            if (previousResources == null) {
                System.clearProperty("compose.application.resources.dir")
            } else {
                System.setProperty("compose.application.resources.dir", previousResources)
            }
            Files.walk(outputDirectory).use { paths ->
                paths.sorted(Comparator.reverseOrder()).forEach(Files::deleteIfExists)
            }
        }
    }
}
