package com.games.gateway.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Locale;

/**
 * 国际化工具类
 *
 * @author zzhan
 * @description 国际化工具
 * @date 2019/5/27 16:43
 */
@Component
public class MessageUtils {

    private static MessageSource messageSource;


    @Autowired
    public void setMessageSource(MessageSource messageSource) {
        MessageUtils.messageSource = messageSource;
    }

    /**
     * 获取单个国际化翻译值
     */
    public static String get(String msgKey) {
        try {
            String message = messageSource.getMessage(msgKey, null, LocaleContextHolder.getLocale());
            return message;
        } catch (Exception e) {
            e.printStackTrace();
            return msgKey;
        }
    }

    public static String get(String msgKey, Locale locale) {
        try {
            String message = messageSource.getMessage(msgKey, null, locale);
            return message;
        } catch (Exception e) {
            return msgKey;
        }
    }

    public static String getMessage(String code, Locale locale) {
        try {
            String message = messageSource.getMessage(code, null, locale);
            return message;
        } catch (Exception e) {
            return code;
        }
    }

    public static String getMessage(String code, Object[] args, Locale locale) {
        return messageSource.getMessage(code, args, locale);
    }

    /**
     * 设置locale
     *
     * @param exchange
     */
    public static void setLocale(ServerWebExchange exchange) {
        String lang = exchange.getRequest().getHeaders().getFirst("accept-language");
        lang = lang == null ? exchange.getRequest().getHeaders().getFirst("Accept-Language") : lang;
        if (lang != null) {
            LocaleContextHolder.setLocale(new Locale(lang));
        }
    }
}
