package com.tt.honeyDue.data

import java.io.File
import java.util.Properties

/**
 * JVM/Desktop implementation of PersistenceManager using Properties file.
 */
actual class PersistenceManager {
    private val properties = Properties()
    private val storageFile: File

    init {
        val userHome = System.getProperty("user.home")
        val appDir = File(userHome, ".honeydue")
        if (!appDir.exists()) {
            appDir.mkdirs()
        }
        storageFile = File(appDir, "data.properties")
        loadProperties()
    }

    private fun loadProperties() {
        if (storageFile.exists()) {
            try {
                storageFile.inputStream().use { properties.load(it) }
            } catch (e: Exception) {
                // Ignore load errors
            }
        }
    }

    private fun saveProperties() {
        try {
            storageFile.outputStream().use { properties.store(it, "honeyDue Data Manager") }
        } catch (e: Exception) {
            // Ignore save errors
        }
    }

    actual fun save(key: String, value: String) {
        properties.setProperty(key, value)
        saveProperties()
    }

    actual fun load(key: String): String? {
        return properties.getProperty(key)
    }

    actual fun remove(key: String) {
        properties.remove(key)
        saveProperties()
    }

    actual fun clear() {
        properties.clear()
        saveProperties()
    }

    companion object {
        private val instance by lazy { PersistenceManager() }

        fun getInstance(): PersistenceManager = instance
    }
}
