package com.qmth.themis.exam.interceptor;

import com.qmth.themis.business.constant.SystemConstant;
import com.qmth.themis.business.entity.SysConfig;
import com.qmth.themis.business.service.ThemisCacheService;
import com.qmth.themis.business.util.AuthUtil;
import com.qmth.themis.business.util.ServletUtil;
import com.qmth.themis.common.enums.ExceptionResultEnum;
import com.qmth.themis.common.enums.Platform;
import com.qmth.themis.common.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Optional;

/**
 * @Description: 鉴权拦截器
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2020/6/27
 */
public class AuthInterceptor implements HandlerInterceptor {

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

    @Resource
    ThemisCacheService themisCacheService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) {
        String url = request.getServletPath();
        String method = request.getMethod();
        if (url.equalsIgnoreCase(SystemConstant.ERROR)) {
            throw new BusinessException(ExceptionResultEnum.NOT_FOUND);
        }
        Platform platform = ServletUtil.getRequestPlatform();
        String deviceId = ServletUtil.getRequestDeviceId();
        String authorization = ServletUtil.getRequestAuthorization();
        long time = ServletUtil.getRequestTime();
        log.info("Start authorization: url:{}, method:{}, platform:{}, deviceId:{}, authorization:{}, time:{}", url,
                method, platform, deviceId, authorization, time);
        SysConfig sysConfig = themisCacheService.addSysConfigCache(SystemConstant.EXAM_COMMON_SYSTEM_URLS);
        Optional.ofNullable(sysConfig).orElseThrow(() -> new BusinessException("未配置exam系统url"));
        return AuthUtil.examAuthInterceptor(platform, deviceId, authorization, time, Arrays.asList(StringUtils.split(sysConfig.getConfigValue(), ",")), request, response);
    }

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

    }

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