package com.bizzan.bitrade.config;


import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.util.StringUtils;

import org.springframework.web.servlet.LocaleResolver;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;


@Configuration
public class MyLocaleResovel implements LocaleResolver {

    /**
     * 将请求 lang（如 id_ID、zh_CN）转为 BCP 47 再构造 Locale，保持与 DB / 属性文件后缀 id_ID 一致。
     * 勿使用 new Locale("in", "ID")：会触发 ResourceBundle 查找 messages_in_ID。
     */
    static Locale parseLocaleTag(String raw) {
        if (StringUtils.isEmpty(raw)) {
            return Locale.SIMPLIFIED_CHINESE;
        }
        String tag = raw.replace("\"", "").trim();
        return I18nResourceBundleMessageSource.localeFromTag(tag);
    }

    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String paramLang = httpServletRequest.getParameter("lang");
        if (!StringUtils.isEmpty(paramLang)) {
            return parseLocaleTag(paramLang);
        }
        String headerLang = httpServletRequest.getHeader("lang");
        if (!StringUtils.isEmpty(headerLang)) {
            return parseLocaleTag(headerLang);
        }
        return Locale.SIMPLIFIED_CHINESE;
    }


    @Override
    public void setLocale(HttpServletRequest httpServletRequest, @Nullable HttpServletResponse
            httpServletResponse, @Nullable Locale locale) {
    }

    @Bean
    public LocaleResolver localeResolver() {
        return new MyLocaleResovel();
    }

}

