package cn.com.qmth.stmms.api.interceptor;

import java.util.List;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.com.qmth.stmms.api.utils.AuthInfoUtils;
import cn.com.qmth.stmms.biz.api.auth.annotation.AuthValidate;
import cn.com.qmth.stmms.biz.api.auth.interfaces.AuthValidator;
import cn.com.qmth.stmms.biz.api.auth.model.AuthInfo;
import cn.com.qmth.stmms.biz.api.auth.service.AuthInfoService;
import cn.com.qmth.stmms.biz.api.auth.service.validator.AuthValidateService;
import cn.com.qmth.stmms.common.utils.RequestUtils;

/**
 * 远程服务接口子模块操作拦截器
 * 
 * @author LS
 * 
 */
public class ApiInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AuthInfoService infoService;

    @Autowired
    private AuthValidateService validateService;

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

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HandlerMethod method = (HandlerMethod) handler;
        AuthValidate validateConfig = method.getMethodAnnotation(AuthValidate.class);
        if (validateConfig != null) {
            AuthInfo auth = infoService.getAuthInfo(AuthInfoUtils.getAuthInfoValue(request));
            List<AuthValidator> validators = validateService.getValidators(validateConfig.value());
            if (validators != null) {
                boolean flag = true;
                int status = 200;
                for (AuthValidator validator : validators) {
                    if (!validator.validate(auth)) {
                        flag = false;
                        status = HttpStatus.UNAUTHORIZED.value();
                        break;
                    }
                }
                if (!flag) {
                    response.sendError(status);
                } else {
                    RequestUtils.setApiUser(request, auth.getLoginUser());
                }
                return flag;
            }
        }
        return true;
    }
}
