package com.ruoyi.common.utils;

import static com.ruoyi.common.constant.Constants.CN;
import static com.ruoyi.common.constant.Constants.ES;
import static com.ruoyi.common.constant.Constants.RU;
import static com.ruoyi.common.constant.Constants.US;

import com.ruoyi.common.utils.spring.SpringUtils;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

/**
 * 获取i18n资源文件
 *
 * @author ruoyi
 */
public class MessageUtils {

    /**
     * 根据消息键和参数 获取消息 委托给spring messageSource
     *
     * @param code 消息键
     * @param args 参数
     * @return 获取国际化翻译值
     */
    public static String message(String code, Object... args) {
        MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
        return messageSource.getMessage(code, args, LocaleContextHolder.getLocale());
    }

    public static String getMessage(String code, Integer index, Object... args) {
        MessageSource messageSource = SpringUtils.getBean(MessageSource.class);
        return messageSource.getMessage(code, args, LOCALES.get(index));
    }

    private static final List<Locale> LOCALES = Arrays.asList(
        new Locale("zh", CN),
        new Locale("en", US),
        new Locale("ru", RU),
        new Locale("es", ES)
    );

    /**
     * 获取国际化翻译值
     *
     * @return
     */
    public static Map<String, String> allMessage(String key, Object... args) {
        MessageSource messageSource = SpringUtils.getBean(MessageSource.class);

        Map<String, String> messages = new HashMap<>();
        for (Locale locale : LOCALES) {
            String messageContent = messageSource.getMessage(key, args, locale);
            messages.put(locale.getCountry(), messageContent);
        }
        return messages;
    }
}
