package ru.myitschool.work.data.repo

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.firstOrNull
import ru.myitschool.work.App
import ru.myitschool.work.data.source.NetworkDataSource

object AuthRepository {
    private const val STORE = "AUTH-STORE"
    private const val TOKEN_KEY = "TOKEN"
    private var tokenCache: String? = null
    suspend fun checkAndSave(text: String): Result<Boolean> {
        return NetworkDataSource.checkAuth(text).onSuccess { success ->
            if (success) {
                tokenCache = text
                App.context.userDataStore.edit { preferences ->
                    val prefKey = stringPreferencesKey(TOKEN_KEY)
                    preferences[prefKey] = text
                }
            }
        }
    }
    suspend fun getToken(): String? {
        if (tokenCache == null) {
            tokenCache = App.context.userDataStore.data
                .firstOrNull()
                ?.let { preferences ->
                    preferences[stringPreferencesKey(TOKEN_KEY)]
                }
        }
        return tokenCache
    }

    suspend fun getToken(login : String, password : String) : Result<String> {
        return NetworkDataSource.getToken(login, password)
    }

    suspend fun logout() {
        tokenCache = null
        App.context.userDataStore.edit { preferences ->
            val prefKey = stringPreferencesKey(TOKEN_KEY)
            preferences.remove(prefKey)
        }
    }

    private val Context.userDataStore: DataStore<Preferences> by preferencesDataStore(name = STORE)
}