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

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

import org.springframework.beans.factory.annotation.Autowired;

import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.biz.user.service.UserService;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.interceptor.CommonInterceptor;
import cn.com.qmth.stmms.common.utils.RequestUtils;

/**
 * Admin模块操作拦截器
 * 
 * @author LS
 * 
 */
public class AdminInterceptor extends CommonInterceptor {

    @Autowired
    private UserService userService;

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

    private boolean validateAdminUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = buildUser(RequestUtils.getWebUser(request));
        if (user != null && (user.getRole() == Role.SYS_ADMIN || user.getRole() == Role.SCHOOL_ADMIN
                || user.getRole() == Role.SUBJECT_HEADER || user.getRole() == Role.SCHOOL_VIEWER)) {
            return true;
        }
        return sessionExpire(request, response, "/admin-login");
    }

    protected User buildUser(WebUser wu) {
        User user = null;
        if (wu != null) {
            user = wu.getUser();
            if (user == null) {
                user = userService.findById(wu.getId());
                if (user != null) {
                    wu.setDataObject(user);
                    wu.setName(user.getName());
                    wu.setRole(user.getRole());
                }
            }
        }
        return user;
    }
}
