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

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

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

import cn.com.qmth.stmms.admin.interceptor.AdminInterceptor;
import cn.com.qmth.stmms.biz.exam.model.ExamStudent;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.common.domain.WebStudent;
import cn.com.qmth.stmms.common.enums.UserType;
import cn.com.qmth.stmms.common.hessian.HessianClientContext;
import cn.com.qmth.stmms.common.utils.RequestUtils;

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

    @Autowired
    private ExamStudentService examStudentService;

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

    private boolean validateStudent(HttpServletRequest request, HttpServletResponse response) throws Exception {
        WebStudent ws = WebStudent.buildFromSession(RequestUtils.getSession(request));
        if (ws != null) {
            RequestUtils.setWebUser(request, ws);
            if (ws.isRegistered()) {
                User user = buildUser(ws);
                if (user != null && user.getType() == UserType.STUDENT) {
                    HessianClientContext.setKey(user.getSchoolId());
                    return true;
                }
            } else {
                ExamStudent es = examStudentService.findById(ws.getId());
                if (es != null) {
                    ws.setDataObject(es);
                    ws.setName(es.getName());
                    return true;
                }
            }
        }
        String uri = request.getRequestURI();
        if (!"/student/login".equals(uri)) {
            return sessionExpire(request, response, "/student-login");
        } else {
            return true;
        }
    }
}
