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

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.iocoder.yudao.framework.common.constant.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

/**
 * RequestContextFilter 会传入默认的Locale，优先级(-105) 要比RequestContextFilter优先级高
 * @author LGH
 */
@Slf4j
@Order(-104)
public class LocaleFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //默认获取Header locale
        String lang = request.getHeader(LocaleChangeInterceptor.DEFAULT_PARAM_NAME);
        //获取request locale
        if (StrUtil.isBlank(lang)) { lang = request.getParameter(LocaleChangeInterceptor.DEFAULT_PARAM_NAME); }
        if (StrUtil.isBlank(lang) || lang.equalsIgnoreCase(Constant.LANG)) { lang = LangEnum.ZH.getLanguage(); }

        LocaleContextHolder.setLocale(new Locale(lang.toLowerCase()));
        filterChain.doFilter(request, response);
    }
}
