package com.cnooc.expert.common.interceptor;

import com.cnooc.expert.common.exception.GlobalErrorCodeConstants;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public abstract class AbstractAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 放过OPTIONS请求
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }

        if (request.getRequestURI().contains("favicon.ico")) {
            return true;
        }

        // Annotation
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            if (handlerMethod.getBean().getClass().isAnnotationPresent(NoAuth.class)) {
                return true;
            }
        }

        /*if (!valid(request)) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); // 401

            return false;
        }*/

        if (!valid(request)) {
            returnJsonResponse(response, HttpStatus.UNAUTHORIZED.value(), GlobalErrorCodeConstants.LOGIN_EXPIRED.getCode(), "Token无效或已过");

            return false;
        }

        return true;
    }

    abstract protected boolean valid(HttpServletRequest request);

    private void returnJsonResponse(HttpServletResponse response, int status, int httpCode, String message) throws IOException {
        response.setStatus(status);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");

        Map<String, Object> result = new HashMap<>();
        result.put("httpCode", httpCode);
        result.put("message", message);

        String json = objectMapper.writeValueAsString(result);
        response.getWriter().write(json);
        response.getWriter().flush();
    }

}
