package de.tsschulz.tt_tagebuch.shared.state

import de.tsschulz.tt_tagebuch.shared.i18n.MobileStrings
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

class LanguageManager(
    private val languageStorage: LanguageStorage,
) {
    private val _state = MutableStateFlow(LanguageState())
    val state: StateFlow<LanguageState> = _state.asStateFlow()

    suspend fun hydrate() {
        val stored = languageStorage.loadLanguageCode()
        val languageCode = stored?.takeIf { code ->
            MobileStrings.supportedLanguages.any { it.code == code }
        } ?: MobileStrings.DEFAULT_LANGUAGE
        _state.value = LanguageState(languageCode)
    }

    suspend fun selectLanguage(languageCode: String) {
        if (MobileStrings.supportedLanguages.none { it.code == languageCode }) return
        languageStorage.saveLanguageCode(languageCode)
        _state.value = LanguageState(languageCode)
    }
}
