package com.bizzan.bitrade.config;

import org.springframework.context.support.ResourceBundleMessageSource;

import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * 印尼语请求使用 lang=id_ID，属性文件为 messages_id_ID.properties。
 * JDK ResourceBundle 在部分版本会把语言码 id 规范为旧 ISO 639 码 in，从而查找 messages_in_ID。
 * 此处对印尼 locale 显式按 id_ID 后缀加载，避免依赖 in_ID 重复文件。
 */
public class I18nResourceBundleMessageSource extends ResourceBundleMessageSource {

    private static final Locale ID_ID = localeFromTag("id_ID");

    @Override
    protected ResourceBundle doGetBundle(String basename, Locale locale) throws MissingResourceException {
        if (isIndonesian(locale)) {
            return super.doGetBundle(basename, ID_ID);
        }
        return super.doGetBundle(basename, locale);
    }

    static Locale localeFromTag(String langTag) {
        if (langTag == null || langTag.isEmpty()) {
            return Locale.SIMPLIFIED_CHINESE;
        }
        return Locale.forLanguageTag(langTag.trim().replace('_', '-'));
    }

    static boolean isIndonesian(Locale locale) {
        if (locale == null) {
            return false;
        }
        String country = locale.getCountry();
        if (!"ID".equalsIgnoreCase(country)) {
            return false;
        }
        String lang = locale.getLanguage();
        return "id".equalsIgnoreCase(lang) || "in".equalsIgnoreCase(lang);
    }
}
