package de.arxsilex.maptools.converter.desktop

import de.arxsilex.maptools.converter.core.GeoBounds
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 PackagedWorkerCropIntegrationTest {
    @Test
    fun `packaged Windows launcher runs optimized crop and waits for output`() {
        val inputValue = System.getenv("MAPTOOLS_PACKAGED_WORKER_CROP_INPUT") ?: return
        val resourcesValue = System.getenv("MAPTOOLS_PACKAGED_WORKER_RESOURCES") ?: return
        val input = Path.of(inputValue)
        val outputDirectory = Files.createTempDirectory("maptools-packaged-crop-test-")
        val cacheDirectory = outputDirectory.resolve("cache")
        val output = outputDirectory.resolve("crop.osm.pbf")
        val previousResources = System.getProperty("compose.application.resources.dir")
        try {
            System.setProperty("compose.application.resources.dir", resourcesValue)
            val result = WorkerLauncher.cropPbf(
                input = input,
                output = output,
                bounds = GeoBounds(west = 8.17, south = 50.05, east = 8.25, north = 50.13),
                cacheDirectory = cacheDirectory,
                temporaryDirectory = outputDirectory,
            )

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