package app.furmeet.events.system.helper

import android.annotation.SuppressLint
import android.content.Context
import android.content.res.Configuration
import android.content.res.Resources
import app.furmeet.events.bff.R
import java.util.*

class LocaleManager(private val context: Context) {
    private val languageFile = context.filesDir.joinFile("language.txt")

    var language: Language
        @SuppressLint("DefaultLocale")
        get() =
            (
                    if (languageFile.exists())
                        languageFile.readText()
                    else
                        ""
                    )
                    .let { if (it.isEmpty()) context.getString(R.string.app_locale) else it }
                    .let { it.toLowerCase() }
                    .let { svd -> Language.values().first { it.name.toLowerCase() == svd } }
        set(lang) = languageFile.writeText(lang.name)


    val locale: Locale get() = language.locale

    val patchedContext = updateResources()

    private fun updateResources(): Context {
        Locale.setDefault(locale)

        val res: Resources = context.resources
        val config = Configuration(res.configuration)

        config.setLocale(locale)

        return context.createConfigurationContext(config)
    }
}