@file:Suppress("HardCodedStringLiteral")

package eu.gaudian.translator.model.repository

import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import eu.gaudian.translator.utils.Log
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

/**
 * A generic wrapper for a single setting in DataStore.
 *
 * @param T The type of the setting value.
 * @param dataStore The DataStore instance.
 * @param key The Preferences.Key for this setting.
 * @param defaultValue The default value to return if none is set.
 */
class Setting<T>(
    private val dataStore: DataStore<Preferences>,
    private val key: Preferences.Key<T>,
    private val defaultValue: T
) {
    /**
     * A Flow that emits the current value of the setting.
     */
    val flow: Flow<T> = dataStore.data.map { preferences ->
        preferences[key] ?: defaultValue
    }

    /**
     * Sets or updates the value of the setting.
     */
    suspend fun set(value: T) {
        Log.d("Setting", "Setting value for key $key to $value")
        dataStore.edit { settings ->
            settings[key] = value
        }
    }
}