/* (C) 2022 YiRing, Inc. */
package com.yiring.common.core;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.PropertyKey;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceResolvable;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 国际化
 *
 * @author Jim
 * @version 0.1
 * 2022/8/17 10:40
 */

@Slf4j
@Order
@Component
@RequiredArgsConstructor
public class I18n {

    public static final String RESOURCE_BUNDLE = "i18n.messages";

    final MessageSource messageSource;

    /**
     * 根据 MessageSourceResolvable 获取 I18n 消息
     *
     * @param resolvable MessageSourceResolvable
     * @return 消息内容
     */
    @SuppressWarnings("unused")
    public String get(MessageSourceResolvable resolvable) {
        return messageSource.getMessage(resolvable, LocaleContextHolder.getLocale());
    }

    /**
     * 根据 code 和注入参数获取 I18n 消息
     * eg:
     * default.nonnull = {0}不能为空
     * message.username.not-empty = 用户姓名不能为空
     * I18n.get("default.nonnull", "用户姓名")
     * I18n.get("message.username.not-empty")
     *
     * @param key  消息标识
     * @param args 注入参数
     * @return 消息内容
     */
    @SuppressWarnings("unused")
    public String get(@PropertyKey(resourceBundle = RESOURCE_BUNDLE) String key, Object... args) {
        return messageSource.getMessage(key, args, LocaleContextHolder.getLocale());
    }

    /**
     * 根据 code 和注入参数获取 I18n 消息
     * eg:
     * default.nonnull = {0}不能为空
     * I18n.get("default.nonnull", "用户姓名")
     * I18n.get("message.username.not-empty", "用户姓名不能为空")
     *
     * @param key            消息标识
     * @param defaultMessage 默认消息
     * @param args           注入参数
     * @return 消息内容
     */
    @SuppressWarnings("unused")
    public String get(
        @PropertyKey(resourceBundle = RESOURCE_BUNDLE) String key,
        String defaultMessage,
        Object... args
    ) {
        return messageSource.getMessage(key, args, defaultMessage, LocaleContextHolder.getLocale());
    }
}
