package com.hermes.app.core.localization

import android.content.Context
import android.content.res.Configuration
import com.hermes.app.R
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import java.util.Locale

class HermesLocalizationStore(private val appContext: Context) {
    private val supportedLocales = setOf("en", "sv")
    private val _localeCode = MutableStateFlow(defaultLocale())

    val localeCode: StateFlow<String> = _localeCode.asStateFlow()

    fun setLocale(localeCode: String) {
        _localeCode.value = normalize(localeCode)
    }

    fun string(resId: Int): String = localizedContext(localeCode.value).getString(resId)

    fun string(localeCode: String, resId: Int): String = localizedContext(normalize(localeCode)).getString(resId)

    fun localeName(targetLocaleCode: String, displayLocaleCode: String = localeCode.value): String {
        val resId = when (normalize(targetLocaleCode)) {
            "sv" -> R.string.locale_swedish
            else -> R.string.locale_english
        }

        return string(displayLocaleCode, resId)
    }

    private fun localizedContext(localeCode: String): Context {
        val configuration = Configuration(appContext.resources.configuration)
        configuration.setLocale(Locale.forLanguageTag(localeCode))
        return appContext.createConfigurationContext(configuration)
    }

    private fun defaultLocale(): String = normalize(Locale.getDefault().language)

    private fun normalize(localeCode: String): String = if (supportedLocales.contains(localeCode)) localeCode else "en"
}
