package de.arxsilex.maptools.converter.desktop

import java.nio.file.Files
import java.sql.DriverManager
import de.arxsilex.maptools.converter.core.GeoBounds
import kotlin.io.path.createTempFile
import kotlin.test.Test
import kotlin.test.assertEquals

class MapsforgePoiSourceTest {
    @Test
    fun `reads and validates version three metadata`() {
        val file = createTempFile(suffix = ".poi")
        try {
            Files.delete(file)
            Class.forName("org.sqlite.JDBC")
            DriverManager.getConnection("jdbc:sqlite:${file.toAbsolutePath()}").use { connection ->
                connection.createStatement().use { statement ->
                    statement.execute("CREATE TABLE metadata (name TEXT, value TEXT)")
                    statement.execute("CREATE TABLE poi_categories (id INTEGER PRIMARY KEY, name TEXT, parent INTEGER)")
                    statement.execute("CREATE TABLE poi_category_map (id INTEGER, category INTEGER, PRIMARY KEY (id, category))")
                    statement.execute("CREATE TABLE poi_data (id INTEGER PRIMARY KEY, data TEXT)")
                    statement.execute("CREATE TABLE poi_index (id INTEGER PRIMARY KEY, lat REAL, lon REAL)")
                    statement.execute(
                        "INSERT INTO metadata VALUES " +
                            "('version', '3'), ('bounds', '50.0,8.0,51.0,9.0'), ('writer', 'test-writer')",
                    )
                    statement.execute("INSERT INTO poi_data VALUES (1, 'name=Test')")
                    statement.execute("INSERT INTO poi_index VALUES (1, 50.5, 8.5)")
                }
            }

            val metadata = MapsforgePoiSource.readMetadata(file)

            assertEquals(3, metadata.schemaVersion)
            assertEquals(1L, metadata.poiCount)
            assertEquals(8.0, metadata.bounds.west)
            assertEquals(51.0, metadata.bounds.north)
            assertEquals("test-writer", metadata.writer)

            val preview = MapsforgePoiSource.loadPreview(file, GeoBounds(8.0, 50.0, 8.7, 50.7))
            assertEquals(1, preview.points.size)
            assertEquals(listOf("Test"), preview.labels.map { it.text })
        } finally {
            Files.deleteIfExists(file)
        }
    }
}
