package com.sckw.core.web.response.result;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Objects;

/**
 * @author lfdc
 * @description
 * @date 2023-09-14 09:09:06
 */
public class I18nMessage {
    private static final Logger log = LoggerFactory.getLogger(I18nMessage.class);
    private static MessageSource messageSource;

    public I18nMessage() {
        throw new IllegalArgumentException("MessageSource can't be null");
    }

    public I18nMessage(MessageSource messageSource) {
        Objects.requireNonNull(messageSource, "MessageSource can't be null");
        I18nMessage.messageSource = messageSource;
    }

    public static String getMessage(String msgCode, Object[] args) {
        try {
            return messageSource.getMessage(msgCode, args, LocaleContextHolder.getLocale());
        } catch (Exception var3) {
            if (log.isDebugEnabled()) {
                var3.printStackTrace();
            }

            log.error("===> 读取国际化消息失败, code:{}, args:{}, ex:{}", new Object[]{msgCode, args, var3.getMessage() == null ? var3.toString() : var3.getMessage()});
            return "-Unknown-";
        }
    }

    public static String getMessage(String msgCode) {
        return getMessage(msgCode, (Object[])null);
    }
}