package dev.fyloz.plannervio.core.service

import dev.fyloz.plannervio.ui.i18n.MergedResourceBundle
import java.util.*

/**
 * Each instance of this service have a specific resource bundle and one for keywords.
 *
 * @param specificBundle The specific bundle. Should only be null when the service uses only the keyword's bundle.
 * @param keywordsBundle The keyword's bundle
 */
class I18nService(specificBundle: ResourceBundle?, keywordsBundle: ResourceBundle) : II18nService {
    override val bundle: ResourceBundle

    init {
        bundle = if (specificBundle == null)
            keywordsBundle
        else
            MergedResourceBundle(specificBundle, keywordsBundle)
    }

    override fun getLocalizedString(key: II18nKey): String {
        return bundle.getString(key.keyName)
    }
}

private const val keywordsServiceKey = "KEYWORDS"
private val keywordsBundle: ResourceBundle = getBundle(keywordsServiceKey.toLowerCase())

private val i18nServices: MutableMap<String, I18nService> = mutableMapOf(
//    keywordsServiceKey to I18nService(null, keywordsBundle)
)

/**
 * Locate an internationalization service for a given bundle name.
 * If no service exists for the given bundle name, it gets created.
 *
 * @param bundleName The bundle's name. If null, an internationalization service using only keywords will be returned.
 */
fun locateI18nService(bundleName: String?): I18nService {
    if (bundleName == null) {
        return getService(keywordsServiceKey)
    }

    if (!i18nServices.containsKey(bundleName)) {
        i18nServices[bundleName] = I18nService(getBundle(bundleName), keywordsBundle)
    }

    return getService(bundleName)
}

/**
 * Gets a internationalization service for a given bundle name.
 * The service should exists before this method gets called.
 *
 * @param bundleName The bundle's name
 * @throws IllegalStateException There was no service created for the bundle's name. (Should never happen)
 */
private fun getService(bundleName: String): I18nService {
    return i18nServices[bundleName]
        ?: throw IllegalStateException("An internationalization service was null after it's creation.") // Should never happen
}

/**
 * Load a bundle for the given bundle name.
 *
 * @param bundleName The bundle's name
 */
private fun getBundle(bundleName: String): ResourceBundle {
    return ResourceBundle.getBundle("lang.${bundleName}")
}
