package ru.myitschool.work.data.source

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 dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import javax.inject.Singleton

@Singleton
class AuthorizationStorageDataSource @Inject constructor(
    @ApplicationContext private val context: Context,
) {
    private val Context.storage: DataStore<Preferences> by preferencesDataStore(name = NAME)
    val login: Flow<String?> = context.storage.data.map { preferences ->
        preferences[LOGIN_KEY]
    }

    suspend fun updateLogin(username: String?) {
        context.storage.edit { settings ->
            if (username != null) {
                settings[LOGIN_KEY] = username
            } else {
                settings.remove(LOGIN_KEY)
            }
        }
    }

    private companion object {
        const val NAME = "auth_data"
        val LOGIN_KEY = stringPreferencesKey("login")
    }
}