package llc.arma.ble.data.repository

import android.app.Application
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
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 kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import llc.arma.ble.domain.model.BleFilter
import llc.arma.ble.domain.repository.SettingsRepository
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class SettingsRepositoryImpl @Inject constructor(
    private val app: Application
) : SettingsRepository {

    val FILTER = stringPreferencesKey("ble_filter")

    val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings")

    override suspend fun saveFilter(
        bleFilter: BleFilter
    ) {
        app.dataStore.edit { settings ->

            settings[FILTER] = Json.encodeToString(bleFilter)
        }
    }

    override fun getFilterFlow(): Flow<BleFilter?> {
        return app.dataStore.data.map { settings ->
            try {

                Json.decodeFromString<BleFilter>(settings[FILTER] ?: "")
            } catch (e: Throwable){
                e.printStackTrace()
                null
            }
        }
    }

}