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

import java.util.Locale;
import lombok.RequiredArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.annotation.Order;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

/**
 * 国际化配置
 *
 * @author Jim
 * @version 0.1
 * 2022/8/17 10:33
 */

@Order
@Configuration
@RequiredArgsConstructor
public class I18nConfig {

    public static final Locale DEFAULT_LOCALE = Locale.SIMPLIFIED_CHINESE;

    /**
     * 解决多模块 i18n/messages 重复文件的读取问题
     * <a href="https://stackoverflow.com/questions/17661252/spring-multi-module-i18n-with-modules-extending-the-messagesource-contents?noredirect=1&lq=1">...</a>
     *
     * @return MessageSource
     */
    @Bean
    public MessageSource messageSource() {
        SmReloadableResourceBundleMessageSource messageSource = new SmReloadableResourceBundleMessageSource();
        messageSource.setBasenames("classpath*:i18n/messages", "classpath*:i18n/status", "classpath:i18n/validation");
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setAlwaysUseMessageFormat(true);
        messageSource.setDefaultLocale(DEFAULT_LOCALE);
        return messageSource;
    }

    @Bean
    public LocaleResolver localeResolver() {
        // header accept-language
        AcceptHeaderLocaleResolver resolver = new AcceptHeaderLocaleResolver();
        resolver.setDefaultLocale(DEFAULT_LOCALE);
        return resolver;
    }

    @Bean
    public LocalValidatorFactoryBean getValidator() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setDefaultEncoding("UTF-8");
        messageSource.setDefaultLocale(DEFAULT_LOCALE);
        messageSource.setBasenames("classpath:/ValidationMessages", "classpath:i18n/validation");
        LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
        bean.setValidationMessageSource(messageSource);
        return bean;
    }
}
