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

import org.apache.commons.lang.StringUtils;

import cn.com.qmth.stmms.biz.exam.model.Marker;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.session.model.StmmsSession;

/**
 * 云阅卷前台已登录用户抽象描述类
 * 
 * @author luoshi
 * 
 */
public class WebUser {

    private static final String SESSION_USER_ID_KEY = "_web_user_id_";

    private static final String SESSION_USER_ROLE_KEY = "_web_user_role_";

    private Integer id;

    private String name;

    private Role role;

    private Object userData;

    public WebUser(Integer id, Role role) {
        this.id = id;
        this.role = role;

        if (id == null || role == null) {
            throw new IllegalArgumentException("webUser init error!");
        }
    }

    public void writeToSession(StmmsSession session) {
        session.setParameter(SESSION_USER_ID_KEY, String.valueOf(id));
        session.setParameter(SESSION_USER_ROLE_KEY, String.valueOf(role.getValue()));
    }

    public static WebUser buildFromSession(StmmsSession session) {
        WebUser wu = null;
        String userId = StringUtils.trimToNull(session.getParameter(SESSION_USER_ID_KEY));
        String userRole = StringUtils.trimToNull(session.getParameter(SESSION_USER_ROLE_KEY));
        if (StringUtils.isNumeric(userId) && StringUtils.isNumeric(userRole)) {
            try {
                wu = new WebUser(Integer.valueOf(userId), Role.findByValue(Integer.valueOf(userRole)));
            } catch (Exception e) {
            }
        }
        return wu;
    }

    public void setDataObject(Object userData) {
        this.userData = userData;
    }

    public User getUser() {
        return userData != null && userData instanceof User ? (User) userData : null;
    }

    public Marker getMarker() {
        return userData != null && userData instanceof Marker ? (Marker) userData : null;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public Role getRole() {
        return role;
    }

    public void setRole(Role role) {
        this.role = role;
    }

    public boolean isSubjectHeader() {
        return role == Role.SUBJECT_HEADER;
    }

    public boolean isSchoolAdmin() {
        return role == Role.SCHOOL_ADMIN;
    }
    
    public boolean isSchoolViewer() {
        return role == Role.SCHOOL_VIEWER;
    }

}
