package com.bonus.common.houqin.i18n;

import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration;
import org.springframework.boot.validation.MessageInterpolatorFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Role;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;

import java.time.Duration;

//@AutoConfiguration(
//   before = {ValidationAutoConfiguration.class}
//)
public class I18nConfiguration {
   public I18nConfiguration(MessageSource messageSource, LocaleResolver localeResolver) {
      I18n.messageSource = messageSource;
      I18n.localeResolver = localeResolver;
   }

   @Bean
   @Role(2)
   @ConditionalOnMissingBean({Validator.class})
   public static LocalValidatorFactoryBean defaultValidator(ApplicationContext applicationContext, MessageSource messageSource) {
      LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
      factoryBean.setValidationMessageSource(messageSource);
      factoryBean.getValidationPropertyMap().put("hibernate.validator.fail_fast", "true");
      factoryBean.setMessageInterpolator((new MessageInterpolatorFactory(applicationContext)).getObject());
      return factoryBean;
   }

   @Bean
   @ConditionalOnMissingBean({LocaleResolver.class})
   public static LocaleResolver localeResolver() {
      CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
      cookieLocaleResolver.setCookieMaxAge(Duration.ofSeconds(2147483647L).getNano());
      return cookieLocaleResolver;
   }
}
