package de.trainingstagebuch.app.services

import android.content.Context
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.os.LocaleListCompat

data class LanguageOption(
    val code: String,
    val labelResId: Int
)

class PersonalSettingsService(
    context: Context
) {
    private val prefs = context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)

    val availableLanguages: List<LanguageOption> = listOf(
        LanguageOption("de", de.trainingstagebuch.app.R.string.personal_settings_language_de),
        LanguageOption("en-US", de.trainingstagebuch.app.R.string.personal_settings_language_en_us),
        LanguageOption("en-GB", de.trainingstagebuch.app.R.string.personal_settings_language_en_gb),
        LanguageOption("fr", de.trainingstagebuch.app.R.string.personal_settings_language_fr),
        LanguageOption("es", de.trainingstagebuch.app.R.string.personal_settings_language_es),
        LanguageOption("it", de.trainingstagebuch.app.R.string.personal_settings_language_it),
        LanguageOption("pl", de.trainingstagebuch.app.R.string.personal_settings_language_pl),
        LanguageOption("ja", de.trainingstagebuch.app.R.string.personal_settings_language_ja),
        LanguageOption("zh", de.trainingstagebuch.app.R.string.personal_settings_language_zh)
    )

    fun currentLanguage(): String {
        return prefs.getString(KEY_LANGUAGE, null)
            ?: AppCompatDelegate.getApplicationLocales().toLanguageTags().takeIf { it.isNotBlank() }
            ?: "de"
    }

    fun setLanguage(code: String) {
        prefs.edit().putString(KEY_LANGUAGE, code).apply()
        AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags(code))
    }

    fun applyPersistedLanguage() {
        val code = prefs.getString(KEY_LANGUAGE, null) ?: return
        AppCompatDelegate.setApplicationLocales(LocaleListCompat.forLanguageTags(code))
    }

    companion object {
        private const val PREFS_NAME = "personal_settings"
        private const val KEY_LANGUAGE = "language"
    }
}
