package com.bonus.common.houqin.i18n;

import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.LocaleResolver;

import java.util.Locale;

public class I18n {
   static MessageSource messageSource;
   static LocaleResolver localeResolver;

   private I18n() {
   }

   public static String getMessage(String message, Object... args) {
      return getMessage(message, LocaleContextHolder.getLocale(), args);
   }

   public static String getMessage(String message, Locale locale, Object... args) {
      return getMessage(message, message, locale, args);
   }

   public static String getMessage(String message, String defaultMessage, Locale locale, Object... args) {
      return messageSource.getMessage(message, args, defaultMessage, locale);
   }

   public static void changeLocale(String newLocale) {
      ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.currentRequestAttributes();
      localeResolver.setLocale(servletRequestAttributes.getRequest(), servletRequestAttributes.getResponse(), StringUtils.parseLocale(newLocale));
   }
}
