package xyz.cottongin.radio247.data.prefs

import android.content.Context
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

class RadioPreferences(private val context: Context) {
    private val dataStore = context.dataStore

    val stayConnected: Flow<Boolean> = dataStore.data.map { it[STAY_CONNECTED] ?: false }
    val bufferMs: Flow<Int> = dataStore.data.map { it[BUFFER_MS] ?: 0 }
    val lastStationId: Flow<Long?> = dataStore.data.map { it[LAST_STATION_ID] }

    val qualityPreference: Flow<String> = dataStore.data.map {
        it[QUALITY_PREFERENCE] ?: DEFAULT_QUALITY_ORDER
    }
    val historyEnabled: Flow<Boolean> = dataStore.data.map { it[HISTORY_ENABLED] ?: false }
    val historyFormat: Flow<String> = dataStore.data.map { it[HISTORY_FORMAT] ?: "csv" }
    val historyDirUri: Flow<String> = dataStore.data.map { it[HISTORY_DIR_URI] ?: "" }

    suspend fun setStayConnected(value: Boolean) {
        dataStore.edit { it[STAY_CONNECTED] = value }
    }

    suspend fun setBufferMs(value: Int) {
        dataStore.edit { it[BUFFER_MS] = value }
    }

    suspend fun setLastStationId(value: Long) {
        dataStore.edit { it[LAST_STATION_ID] = value }
    }

    suspend fun setQualityPreference(value: String) {
        dataStore.edit { it[QUALITY_PREFERENCE] = value }
    }

    suspend fun setHistoryEnabled(value: Boolean) {
        dataStore.edit { it[HISTORY_ENABLED] = value }
    }

    suspend fun setHistoryFormat(value: String) {
        dataStore.edit { it[HISTORY_FORMAT] = value }
    }

    suspend fun setHistoryDirUri(value: String) {
        dataStore.edit { it[HISTORY_DIR_URI] = value }
    }

    companion object {
        private val Context.dataStore by preferencesDataStore(name = "radio_prefs")
        private val STAY_CONNECTED = booleanPreferencesKey("stay_connected")
        private val BUFFER_MS = intPreferencesKey("buffer_ms")
        private val LAST_STATION_ID = longPreferencesKey("last_station_id")
        private val QUALITY_PREFERENCE = stringPreferencesKey("quality_preference")
        private val HISTORY_ENABLED = booleanPreferencesKey("history_enabled")
        private val HISTORY_FORMAT = stringPreferencesKey("history_format")
        private val HISTORY_DIR_URI = stringPreferencesKey("history_dir_uri")

        const val DEFAULT_QUALITY_ORDER = """["256-ssl","256-nossl","128-ssl","128-nossl"]"""
    }
}
