package de.arxsilex.maptools.converter.desktop

import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.StandardCopyOption
import java.util.Locale
import java.util.Properties

internal enum class MeasurementSystem(val persistedValue: String) {
    METRIC("metric"),
    IMPERIAL("imperial");

    companion object {
        fun fromPersistedValue(value: String?): MeasurementSystem? = entries.firstOrNull {
            it.persistedValue.equals(value, ignoreCase = true)
        }
    }
}
internal data class AppPreferences(
    val language: AppLanguage,
    val measurementSystem: MeasurementSystem,
)

internal object AppPreferencesStore {
    private const val LANGUAGE_KEY = "language"
    private const val MEASUREMENT_SYSTEM_KEY = "measurementSystem"

    fun settingsFile(applicationDirectory: Path = PlatformDirectories.applicationDirectory()): Path =
        applicationDirectory.toAbsolutePath().normalize().resolve("settings").resolve("preferences.properties")

    fun load(
        file: Path = settingsFile(),
        systemLocale: Locale = Locale.getDefault(),
    ): AppPreferences {
        val properties = Properties()
        if (Files.isRegularFile(file)) {
            runCatching { Files.newInputStream(file).use(properties::load) }
        }
        return AppPreferences(
            language = AppLanguage.fromTag(properties.getProperty(LANGUAGE_KEY))
                ?: AppLanguage.systemDefault(systemLocale),
            measurementSystem = MeasurementSystem.fromPersistedValue(properties.getProperty(MEASUREMENT_SYSTEM_KEY))
                ?: MeasurementSystem.METRIC,
        )
    }

    fun save(preferences: AppPreferences, file: Path = settingsFile()) {
        Files.createDirectories(requireNotNull(file.parent))
        val temporary = file.resolveSibling("${file.fileName}.tmp")
        val properties = Properties().apply {
            setProperty(LANGUAGE_KEY, preferences.language.tag)
            setProperty(MEASUREMENT_SYSTEM_KEY, preferences.measurementSystem.persistedValue)
        }
        Files.newOutputStream(temporary).use { output ->
            properties.store(output, "ArxSilex MapTools Converter portable preferences")
        }
        runCatching {
            Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE)
        }.getOrElse {
            Files.move(temporary, file, StandardCopyOption.REPLACE_EXISTING)
        }
    }
}
