package cn.com.qmth.examcloud.tool.config;

import cn.com.qmth.examcloud.tool.vo.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

public class AccessInterceptor extends HandlerInterceptorAdapter {

    private final static Logger log = LoggerFactory.getLogger(AccessInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getSession().getAttribute(Constants.LOGIN_USER) == null) {
            String path = request.getServletPath();
            if (path.startsWith("/api")) {
                this.renderJson(response, HttpStatus.FORBIDDEN, "禁止访问，请先登录！");
            } else {
                response.sendRedirect("/login");
            }
            return false;
        }

        return true;
    }

    private void renderJson(HttpServletResponse response, HttpStatus httpStatus, String msg) {
        PrintWriter out = null;
        try {
            response.setStatus(httpStatus.value());
            response.setCharacterEncoding("UTF-8");
            response.setContentType(Constants.CONTENT_TYPE_JSON);
            out = response.getWriter();
            out.print(new Result<>(String.valueOf(httpStatus.value()), msg));
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}
