package org.dromara.common.web.core;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.dromara.common.core.utils.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import java.util.Locale;

/**
 * 获取请求头国际化信息
 *
 * @author Lion Li
 */
public class I18nLocaleResolver implements LocaleResolver {

    @Override
    public Locale resolveLocale(HttpServletRequest httpServletRequest) {
        String language = httpServletRequest.getHeader("content-language");
        if (StringUtils.isBlank(language)) {
            language = httpServletRequest.getParameter("lang");
        }
        if (StringUtils.isBlank(language)) {
            language = httpServletRequest.getHeader("Accept-Language");
        }
        if (StringUtils.isBlank(language)) {
            return Locale.SIMPLIFIED_CHINESE;
        }
        String languageTag = language.split(",")[0].trim().replace('_', '-');
        if ("zh".equalsIgnoreCase(languageTag)) {
            return Locale.SIMPLIFIED_CHINESE;
        }
        if ("en".equalsIgnoreCase(languageTag)) {
            return Locale.US;
        }
        Locale locale = Locale.forLanguageTag(languageTag);
        return StringUtils.isBlank(locale.getLanguage()) ? Locale.SIMPLIFIED_CHINESE : locale;
    }

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

    }
}
