package pl.firmatpp.kierowca.data

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import pl.firmatpp.kierowca.ui.theme.AppThemeMode

private val Context.driverAppPreferencesDataStore by preferencesDataStore(name = "driver_app_preferences")

class AppPreferencesStore(
    private val dataStore: DataStore<Preferences>,
) {
    constructor(context: Context) : this(context.driverAppPreferencesDataStore)

    private val themeModeKey = stringPreferencesKey("theme_mode")
    private val routeProgressNotificationEnabledKey = booleanPreferencesKey("route_progress_notification_enabled")

    val themeMode: Flow<AppThemeMode> = dataStore.data
        .map { preferences -> AppThemeMode.fromStoredValue(preferences[themeModeKey]) }

    val routeProgressNotificationEnabled: Flow<Boolean> = dataStore.data
        .map { preferences -> preferences[routeProgressNotificationEnabledKey] ?: true }

    suspend fun setThemeMode(themeMode: AppThemeMode) {
        dataStore.edit { preferences ->
            preferences[themeModeKey] = themeMode.storedValue
        }
    }

    suspend fun setRouteProgressNotificationEnabled(enabled: Boolean) {
        dataStore.edit { preferences ->
            preferences[routeProgressNotificationEnabledKey] = enabled
        }
    }
}
