package com.hs.admin.common.intercepters;

import com.hs.admin.common.Constants;
import com.hs.admin.common.Result;
import com.hs.admin.common.utils.TokenUtil;
import org.slf4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginInterceptor implements HandlerInterceptor {
    Logger logger = org.slf4j.LoggerFactory.getLogger(LoginInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception {
        System.out.println("LoginInterceptor----------->preHandle");

        String token = request.getHeader(Constants.TOKEN_KEY);
        if(!TokenUtil.checkToken(token)){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter writer = null;
            try{
                String remoteHost = request.getRemoteHost();
                String uri = request.getRequestURI();
                logger.info(remoteHost + " 访问 " + uri + ", token无效, token：[" + token + "]");

                writer = response.getWriter();
                writer.print(Result.error(Result.ErrorCode.INVALID_TOKEN));
            }catch(IOException e){
                logger.error(e.getMessage());
            }finally{
                if(writer != null){
                    writer.close();
                }
            }
            return false;
        }

        return HandlerInterceptor.super.preHandle(request,response,handler);
    }

    @Override
    public void postHandle(HttpServletRequest request,HttpServletResponse response,Object handler,ModelAndView modelAndView) throws Exception {
        System.out.println("LoginInterceptor----------->postHandle");


        HandlerInterceptor.super.postHandle(request,response,handler,modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,Object handler,Exception ex) throws Exception {
        System.out.println("LoginInterceptor------->afterCompletion");


        HandlerInterceptor.super.afterCompletion(request,response,handler,ex);
    }
}
