package com.img.rabbit.provider.storage

import android.content.Context
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.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

private val Context.storeData: DataStore<Preferences> by preferencesDataStore(name = "global_state")

class GlobalStateManager(
    private val context: Context
) {
    companion object {
        private val GLOBAL_LOADING = booleanPreferencesKey("global_loading")
        private val GLOBAL_WX_AUTHORIZATION = stringPreferencesKey("global_wx_authorization")
        private val GLOBAL_LOGOUT = booleanPreferencesKey("global_logout")
    }

    suspend fun storeGlobalLoading(value: Boolean) {
        context.storeData.edit { preferences ->
            preferences[GLOBAL_LOADING] = value
        }
    }
    fun isGlobalLoadingFlow(): Flow<Boolean?> {
        return context.storeData.data.map {
                preferences ->
            preferences[GLOBAL_LOADING]
        }
    }



    suspend fun storeGlobalWxAuthorization(value: String) {
        context.storeData.edit { preferences ->
            preferences[GLOBAL_WX_AUTHORIZATION] = value
        }
    }
    fun globalWxAuthorizationFlow(): Flow<String?> {
        return context.storeData.data.map {
                preferences ->
            preferences[GLOBAL_WX_AUTHORIZATION]
        }
    }


    suspend fun storeGlobalLogout(value: Boolean) {
        context.storeData.edit { preferences ->
            preferences[GLOBAL_LOGOUT] = value
        }
    }
    fun globalLogoutFlow(): Flow<Boolean?> {
        return context.storeData.data.map {
                preferences ->
            preferences[GLOBAL_LOGOUT]
        }
    }

}