package de.arxsilex.maptools.converter.core.preview

import de.arxsilex.maptools.converter.core.GeoBounds
import java.nio.file.Files
import kotlin.io.path.createTempDirectory
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue

class PreviewDatasetStoreTest {
    @Test
    fun `round trips preview cache`() {
        val directory = createTempDirectory("maptools-preview")
        val source = directory.resolve("source.pbf")
        val cache = directory.resolve("preview.mtpv")
        Files.write(source, byteArrayOf(1, 2, 3))
        val cached = CachedPreviewDataset(
            Files.size(source),
            Files.getLastModifiedTime(source).toMillis(),
            "0".repeat(64),
            PreviewDataset(
                GeoBounds(7.0, 49.0, 10.0, 52.0),
                listOf(PreviewPoint(50.0, 8.0, PreviewFeatureClass.POI)),
                listOf(PreviewPolyline(doubleArrayOf(8.0, 50.0, 8.1, 50.1), PreviewFeatureClass.MAJOR_ROAD)),
                12,
                3,
                listOf(PreviewLabel(50.1, 8.1, "Teststadt", PreviewLabelClass.TOWN, 90)),
            ),
        )
        try {
            PreviewDatasetStore.write(cached, cache)
            val restored = PreviewDatasetStore.read(cache)

            assertEquals(cached.sourceSha256, restored.sourceSha256)
            assertEquals(cached.dataset.points, restored.dataset.points)
            assertEquals(cached.dataset.labels, restored.dataset.labels)
            assertTrue(cached.dataset.polylines.single().coordinates.contentEquals(restored.dataset.polylines.single().coordinates))
            assertTrue(PreviewDatasetStore.matchesSource(restored, source))
        } finally {
            directory.toFile().deleteRecursively()
        }
    }

    @Test
    fun `cache persistence failure is reportable without losing the preview`() {
        val directory = createTempDirectory("maptools-preview-warning")
        val blockedParent = directory.resolve("not-a-directory")
        Files.write(blockedParent, byteArrayOf(1))
        val cached = CachedPreviewDataset(
            sourceSize = 1,
            sourceLastModifiedMillis = 1,
            sourceSha256 = "0".repeat(64),
            dataset = PreviewDataset(GeoBounds(7.0, 49.0, 10.0, 52.0), emptyList(), emptyList(), 0, 0),
        )
        try {
            val warning = PreviewDatasetStore.writeBestEffort(cached, blockedParent.resolve("preview.mtpv"))
            assertNotNull(warning)
            assertTrue(warning.contains("Cache", ignoreCase = true))
        } finally {
            directory.toFile().deleteRecursively()
        }
    }
}
