package cn.iocoder.yudao.framework.i18n.core;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author LGH
 */
@Slf4j
public class LocaleInterceptor extends LocaleChangeInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String locale = request.getHeader(getParamName());
        //获取request locale
        if (StrUtil.isBlank(locale)) { locale = request.getParameter(getParamName()); }
        if (StrUtil.isBlank(locale)) { locale = Constant.LANG; }

        if (StrUtil.isNotBlank(locale)) {
                LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
                if (localeResolver == null) {
                    throw new IllegalStateException("No LocaleResolver found: not in a DispatcherServlet request");
                }
                try {
                    localeResolver.setLocale(request, response, parseLocaleValue(locale));
                }
                catch (IllegalArgumentException ex) {
                    if (isIgnoreInvalidLocale()) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Ignoring invalid locale value [" + locale + "]: " + ex.getMessage());
                        }
                    }
                    else {
                        throw ex;
                    }
                }
        }
        return true;
    }
}
