package com.inspect.common.security.interceptor;

import com.inspect.base.core.constant.SecurityConstants;
import com.inspect.base.core.context.SecurityContextHolder;
import com.inspect.base.core.utils.ServletUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.common.security.auth.AuthUtil;
import com.inspect.common.security.utils.SecurityUtils;
import com.inspect.system.base.model.LoginUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import java.lang.reflect.Method;
import java.util.Map;

public class HeaderInterceptor implements AsyncHandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            SecurityContextHolder.setUserId(ServletUtils.getHeader(request, "user_id"));
            SecurityContextHolder.setUserName(ServletUtils.getHeader(request, "username"));
            SecurityContextHolder.setUserKey(ServletUtils.getHeader(request, SecurityConstants.USER_KEY));
            String token = SecurityUtils.getToken();
            if (StringUtils.isNotEmpty(token)) {
                LoginUser loginUser = AuthUtil.getLoginUser(token);
                if (StringUtils.isNotNull(loginUser)) {
                    AuthUtil.verifyLoginUserExpire(loginUser);
                    SecurityContextHolder.set(SecurityConstants.LOGIN_USER, loginUser);
                }
            }

            if (request.getRequestURI().contains("/task/teskRationList")) {
                String redirectUri = "/task/taskRationalList";
                System.out.println("!!! GABRIEL redirectUri: " + redirectUri);
                request.getRequestDispatcher(redirectUri).forward(request, response);
                return false;
            }
        }
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        SecurityContextHolder.remove();
    }
}
