package com.ruoyi.i18n.interceptor;


import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.Locale;

public class MyLocaleChangeInterceptor implements HandlerInterceptor {
    private final static String paramName = "language";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // cookie :language=en_US
        // header :language=en_US
        // parameter :language=en_US
        //通过制定cookie,header,param
        // 获取本地语言的优先级  cookie<header<parameter
        String locale="";
        //1、处理cookie中带有的语言信息
        Cookie cookie = WebUtils.getCookie(request, paramName);
        String cookieLocale="";
        if (cookie!=null) {
            // Proceed in cookie
            cookieLocale=cookie.getValue();
        }
        if(cookieLocale!=null&& !"".equals(cookieLocale.trim())){
            locale=cookieLocale;
        }

        // 2、每次请求的header中可以单独指定语言  language=zh_CN
        String headerLocale = request.getHeader(paramName);

//        System.out.println((request.getHeader("accept-language")));
//        System.out.println(request.getHeader("cookie"));

        if(headerLocale!=null && !"".equals(headerLocale.trim())){
            locale=headerLocale;
        }
        // 3、从get 参数数据获取 language=zh_CN
        String parameterLocale=request.getParameter(paramName);
        if(parameterLocale!=null && !"".equals(parameterLocale.trim())){
            locale=parameterLocale;
        }
        //4 语言信息写入线程变量
        if (locale!=null) {
            LocaleContextHolder.setLocale(parseLocaleValue(locale));
        }

        return true;
    }

    @Nullable
    protected Locale parseLocaleValue(String localeValue) {
        return StringUtils.parseLocale(localeValue);
    }

}