package com.zxhyis.toolss.ad

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.SharedPreferencesMigration
import androidx.datastore.preferences.core.Preferences
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
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking

private const val USER_PREFERENCES_NAME = "settings"

val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
    name = USER_PREFERENCES_NAME,
//    produceMigrations = { context ->
//        listOf(SharedPreferencesMigration(context, USER_PREFERENCES_NAME))
//    }
)

val INSTALL_INFO = stringPreferencesKey("install_info_source")

//第一次启动时间
val FIRST_LAUNCH_TIME_KEY = longPreferencesKey("install_info")

//上次与推送通知时间
val ALL_LAST_PUSH_TIME = longPreferencesKey("all_last_push_time")

//是否是黑名单
val SP_IS_BLACKLIST= booleanPreferencesKey("sp_is_blacklist")

fun getStringKey(string: String): Preferences.Key<String> {
    return stringPreferencesKey(string)
}

fun getLongKey(string: String): Preferences.Key<Long> {
    return longPreferencesKey(string)
}

fun createByActionId(actionId: Int): Preferences.Key<Long> {
    return longPreferencesKey("actionId_$actionId")
}

fun getLongString(string: String): Preferences.Key<Long> {
    return longPreferencesKey(string)
}

fun getIntString(string: String): Preferences.Key<Int> {
    return intPreferencesKey(string)
}

suspend fun <T> Context.saveDataStore(key: Preferences.Key<T>, any: T) {
    dataStore.edit { it[key] = any }
}

fun <T> Context.saveDataStoreBlock(key: Preferences.Key<T>, any: T) {
    runBlocking {
        dataStore.edit { it[key] = any }
    }
}


suspend fun <T> Context.queryDataStore(key: Preferences.Key<T>, action: suspend (any: T?) -> Unit) {
    val flow = dataStore.data.map { it[key] }
    action.invoke(flow.first())
}

/**
 * 同步方式查询
 */
fun <T> Context.queryDataStoreBlock(key: Preferences.Key<T>, defValue: T): T {
    var value = defValue
    runBlocking {
        val flow = dataStore.data.map { preferences ->
            preferences[key] ?: defValue
        }
        value = flow.first()
    }
    return value
}