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.floatPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import com.example.livingai.domain.model.SettingsData
import com.example.livingai.domain.repository.AppDataRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import java.io.IOException

class AppDataRepositoryImpl(private val dataStore: DataStore<Preferences>) : AppDataRepository {

    private object PreferencesKeys {
        val APP_ENTRY = booleanPreferencesKey("app_entry")
        val LANGUAGE = stringPreferencesKey("language")
        val IS_AUTO_CAPTURE_ON = booleanPreferencesKey("is_auto_capture_on")
        val JACCARD_THRESHOLD = floatPreferencesKey("jaccard_threshold")
    }

    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
            val jaccardThreshold = it[PreferencesKeys.JACCARD_THRESHOLD] ?: 50f
            SettingsData(language, isAutoCaptureOn, jaccardThreshold)
        }
    }

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

    override suspend fun saveAppEntry() {
        dataStore.edit { settings ->
            settings[PreferencesKeys.APP_ENTRY] = true
        }
    }

    override fun readAppEntry(): Flow<Boolean> {
        return dataStore.data.map { preferences ->
            preferences[PreferencesKeys.APP_ENTRY] ?: false
        }
    }
}