
package com.tmerclub.cloud.common.i18n;


import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.common.constant.Constant;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Locale;

/**
 * RequestContextFilter 会传入默认的Locale，优先级(-105) 要比RequestContextFilter优先级高
 * @author tmerclub
 */
@Component
@Order(-104)
public class LuckLocaleChangeFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(LuckLocaleChangeFilter.class);
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 设置国际化语言
        String newLocale = request.getHeader("locale");
        // 目前只有中文
        LocaleContextHolder.setLocale(new Locale(LanguageEnum.LANGUAGE_ZH_CN.getLanguage()));
//        LocaleContextHolder.setLocale(getLocal(newLocale));
        filterChain.doFilter(request, response);
    }

    private static Locale getLocal(String langStr) {
        if (langStr == null) {
            return getDefaultLocal();
        }

        if (!StrUtil.contains(langStr, Constant.UNDERLINE)) {
            return new Locale(langStr);
        }
        String[] s = langStr.split(Constant.UNDERLINE);
        if (s.length > 1) {
            return new Locale(s[0], s[1]);
        }
        // 数组长度不够代表前端传的语言编码格式有问题，但这里不能报错，所以要判断下长度>1，否则一旦格式出现问题，所有接口都无法使用
        // 改为使用默认语言
        return getDefaultLocal();
    }


    private static Locale getDefaultLocal() {
        String langStr = LanguageEnum.LANGUAGE_ZH_CN.getLanguage();
        return new Locale(langStr);
    }
}
