package org.octopus.randomfacts.core.shared

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.first

object PreferenceDataStore {

    val Context.dataStore by preferencesDataStore(name = "coins_prefs")
    val COINS_KEY = intPreferencesKey("coins")
    val LAST_UPDATE_KEY = longPreferencesKey("last_update")
    val LAST_FACT_KEY = stringPreferencesKey("last_fact")
    val UNLOCK_PAYWALL_KEY = booleanPreferencesKey("unlocked")

    suspend fun saveCoins(context: Context, coins: Int) {
        context.dataStore.edit { prefs ->
            prefs[COINS_KEY] = coins
        }
    }

    suspend fun loadCoins(context: Context): Int {
        val prefs = context.dataStore.data.first()
        val coins = prefs[COINS_KEY] ?: Const.MAX_COINS
        return coins
    }

    suspend fun saveTimestamp(context: Context, timestamp: Long) {
        context.dataStore.edit { prefs ->
            prefs[LAST_UPDATE_KEY] = timestamp
        }
    }

    suspend fun loadTimestamp(context: Context): Long {
        val prefs = context.dataStore.data.first()
        return  prefs[LAST_UPDATE_KEY] ?: System.currentTimeMillis()
    }



    suspend fun saveFact(context: Context, fact: String) {
        context.dataStore.edit { prefs ->
            prefs[LAST_FACT_KEY] = fact
        }
    }

    suspend fun loadFact(context: Context): String {
        val prefs = context.dataStore.data.first()
        return  prefs[LAST_FACT_KEY] ?: Const.DEFAULT_FACT_PLACEHOLDER
    }

    suspend fun saveUnlocked(context: Context, unlocked: Boolean) {
        context.dataStore.edit { prefs ->
            prefs[UNLOCK_PAYWALL_KEY] = unlocked
        }
    }

    suspend fun loadUnlocked(context: Context): Boolean {
        return context.dataStore.data.first()[UNLOCK_PAYWALL_KEY] == true
    }


}