package de.softwareapp_hb.privateqrscanner.settings

import android.content.Context
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.preferencesDataStore
import de.softwareapp_hb.privateqrscanner.i18n.AppLocaleCatalog
import de.softwareapp_hb.privateqrscanner.ui.UseCaseView
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

private val Context.dataStore by preferencesDataStore(name = "clean_scanner_settings")

class SettingsRepository(private val context: Context) {
    private object Keys {
        val historyEnabled = booleanPreferencesKey("history_enabled")
        val warningsEnabled = booleanPreferencesKey("warnings_enabled")
        val scanFeedbackEnabled = booleanPreferencesKey("scan_feedback_enabled")
        val useCaseView = stringPreferencesKey("use_case_view")
        val appLanguageTag = stringPreferencesKey("app_language_tag")
    }

    val historyEnabled: Flow<Boolean> = context.dataStore.data.map { prefs ->
        prefs[Keys.historyEnabled] ?: false
    }

    val warningsEnabled: Flow<Boolean> = context.dataStore.data.map { prefs ->
        prefs[Keys.warningsEnabled] ?: true
    }

    val scanFeedbackEnabled: Flow<Boolean> = context.dataStore.data.map { prefs ->
        prefs[Keys.scanFeedbackEnabled] ?: true
    }

    val useCaseView: Flow<UseCaseView> = context.dataStore.data.map { prefs ->
        UseCaseView.fromStorageKey(prefs[Keys.useCaseView])
    }

    val appLanguageTag: Flow<String> = context.dataStore.data.map { prefs ->
        prefs[Keys.appLanguageTag] ?: AppLocaleCatalog.SYSTEM_STORAGE_TAG
    }

    suspend fun setHistoryEnabled(enabled: Boolean) {
        context.dataStore.edit { it[Keys.historyEnabled] = enabled }
    }

    suspend fun setWarningsEnabled(enabled: Boolean) {
        context.dataStore.edit { it[Keys.warningsEnabled] = enabled }
    }

    suspend fun setScanFeedbackEnabled(enabled: Boolean) {
        context.dataStore.edit { it[Keys.scanFeedbackEnabled] = enabled }
    }

    suspend fun setUseCaseView(useCaseView: UseCaseView) {
        context.dataStore.edit { it[Keys.useCaseView] = useCaseView.storageKey }
    }

    suspend fun setAppLanguageTag(languageTag: String) {
        context.dataStore.edit { it[Keys.appLanguageTag] = languageTag }
    }
}
