package com.example.livingai.data.repository

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.emptyPreferences
import androidx.datastore.preferences.core.stringPreferencesKey
import com.example.livingai.data.local.model.SettingsData
import com.example.livingai.domain.repository.SettingsRepository
import com.example.livingai.utils.Constants.APP_ENTRY
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import java.io.IOException

class SettingsRepositoryImpl(private val dataStore: DataStore<Preferences>) : SettingsRepository {

    private object PreferencesKeys {
        val LANGUAGE = stringPreferencesKey("language")
        val IS_AUTO_CAPTURE_ON = booleanPreferencesKey("is_auto_capture_on")
    }

    override fun getSettings(): Flow<SettingsData> {
        return dataStore.data.catch {
            if (it is IOException) {
                emit(emptyPreferences())
            } else {
                throw it
            }
        }.map {
            val language = it[PreferencesKeys.LANGUAGE] ?: "en"
            val isAutoCaptureOn = it[PreferencesKeys.IS_AUTO_CAPTURE_ON] ?: false
            SettingsData(language, isAutoCaptureOn)
        }
    }

    override suspend fun saveSettings(settings: SettingsData) {
        dataStore.edit {
            it[PreferencesKeys.LANGUAGE] = settings.language
            it[PreferencesKeys.IS_AUTO_CAPTURE_ON] = settings.isAutoCaptureOn
        }
    }
}