package com.crm.rely.backend.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContextUtils;

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

/**
 * Created by max on 2019/3/7.
 */
public class LocaleInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        setLocale(request, response);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

        setLocale(request, response);
    }

    private void setLocale(HttpServletRequest request, HttpServletResponse response) {
        String lang = request.getParameter("lang");
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        if (lang == null) {
            lang = "zh";
        }
        if ("en".equals(lang)) {
            localeResolver.setLocale(request, response, new Locale("en", "US"));
        } else {
            localeResolver.setLocale(request, response, new Locale("zh", "CN"));
        }
    }
}
