package cl.homelogic.platform.common.settings

import cl.homelogic.platform.common.logging.Trace
import cl.homelogic.platform.common.logging.TreeRoots
import com.russhwolf.settings.Settings

interface ISettingsSource {
    fun <T> get(
        key: PreferenceKey<T>,
        defaultValue: T,
    ): T

    fun <T> set(
        key: PreferenceKey<T>,
        value: T,
    )

    fun <T> remove(key: PreferenceKey<T>)

    fun clear()
}

class SettingsSource(
    private val settings: Settings,
) : ISettingsSource {
    // TODO: add fuction to check if key exists

    override fun <T> get(
        key: PreferenceKey<T>,
        defaultValue: T,
    ): T {
        Trace.d(TreeRoots.Settings, "Retrieving setting: ${key.key}")
        return key.getValue(settings, defaultValue)
    }

    override fun <T> set(
        key: PreferenceKey<T>,
        value: T,
    ) {
        Trace.d(TreeRoots.Settings, "Storing setting: ${key.key} : $value")
        key.setValue(settings, value)
    }

    override fun <T> remove(key: PreferenceKey<T>) {
        Trace.d(TreeRoots.Settings, "Removing setting: ${key.key}")
        settings.remove(key.key)
    }

    override fun clear() {
        Trace.d(TreeRoots.Settings, "Deleting all settings")
        settings.clear()
    }
}

interface ISettingsFactory {
    fun createSettings(name: String? = null): Settings
}
