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_LOGIN_NOTIFY = booleanPreferencesKey("global_login_notify")
        private val GLOBAL_LOGOUT_NOTIFY = booleanPreferencesKey("global_logout_notify")
        private val GLOBAL_UNBIND_NOTIFY = booleanPreferencesKey("global_unbind_notify")
    }

    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 storeGlobalLoginNotify(value: Boolean) {
        context.storeData.edit { preferences ->
            preferences[GLOBAL_LOGIN_NOTIFY] = value
        }
    }
    fun globalLoginNotifyFlow(): Flow<Boolean?> {
        return context.storeData.data.map {
                preferences ->
            preferences[GLOBAL_LOGIN_NOTIFY]
        }
    }

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


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

}