package com.tomhempel.rbarometer

/**
 * Resolves UI strings from API translations (synced from the website).
 * No embedded translation tables — configure strings in the admin Translations UI.
 */
object LanguageManager {
    /** Global app UI strings from GET ?translations=1 */
    private var apiTranslations: Map<String, Map<String, String>> = emptyMap()
    /** Questionnaire-specific strings from GET ?id=... */
    private var questionnaireTranslations: Map<String, Map<String, String>> = emptyMap()

    fun setApiTranslations(translations: Map<String, Map<String, String>>) {
        apiTranslations = translations
    }

    fun setQuestionnaireTranslations(translations: Map<String, Map<String, String>>) {
        questionnaireTranslations = translations
    }

    fun clearQuestionnaireTranslations() {
        questionnaireTranslations = emptyMap()
    }

    fun getTextFormatted(languageId: String, key: String, vararg args: Any): String {
        val raw = getText(languageId, key)
        return String.format(raw, *args)
    }

    fun getText(languageCode: String, id: String): String {
        val lang = apiLanguageCode(languageCode)
        val raw = questionnaireTranslations[lang]?.get(id)
            ?: apiTranslations[lang]?.get(id)
            ?: apiTranslations["de"]?.get(id)
            ?: id
        return injectDynamicValues(raw)
    }

    private fun apiLanguageCode(languageCode: String): String = when (languageCode) {
        "GERMAN" -> "de"
        "ENGLISH" -> "en"
        "FRENCH" -> "fr"
        "ROMANIAN" -> "ro"
        "ARABIC" -> "ar"
        "POLISH" -> "pl"
        "TURKISH" -> "tr"
        "UKRAINIAN" -> "uk"
        "RUSSIAN" -> "ru"
        "SPANISH" -> "es"
        else -> languageCode.lowercase()
    }

    private fun injectDynamicValues(text: String): String = text
}
