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

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

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.com.qmth.stmms.common.auth.annotation.AuthRequire;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.Auth;
import cn.com.qmth.stmms.common.utils.RequestUtils;
import cn.com.qmth.stmms.common.utils.RoleAuthUtils;

/**
 * 方法操作拦截器
 * 
 * @author LS
 * 
 */
public class MethodInterceptor extends HandlerInterceptorAdapter {

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

    private static final String AUTH_FAILE_REDIRECT = "/admin-login";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        return (handler instanceof HandlerMethod) && validateAuth((HandlerMethod) handler, request, response);
    }

    private boolean validateAuth(HandlerMethod method, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        boolean result = true;
        WebUser wu = RequestUtils.getWebUser(request);
        AuthRequire authRequire = method.getMethodAnnotation(AuthRequire.class);
        if (wu != null && authRequire != null) {
            Auth[] auths = authRequire.value();
            if (auths != null) {
                int count = 0;
                for (Auth auth : auths) {
                    if (RoleAuthUtils.hasAuth(wu, auth)) {
                        count++;
                    } else if (!authRequire.isAny()) {
                        result = false;
                        break;
                    }
                }
                if (authRequire.isAny() && count == 0) {
                    result = false;
                }
            }
        }
        if (!result) {
            String redirect = StringUtils.trimToNull(authRequire.redirect());
            response.sendRedirect(request.getContextPath() + (redirect != null ? redirect : AUTH_FAILE_REDIRECT));
            log.info("method auth vaildate faile!");
        }
        return result;
    }
}
