package com.ht.util;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ht.web.hessian.HessianFactoryManger;
import com.ht.web.mongo.domain.User;

public enum UserSession {
	INSTANCE;

	private static final Logger log = LoggerFactory
			.getLogger(UserSession.class);
	
	private long lastLoginTime = -1;
	private final int maxSessionTime = 1000 * 60 * 10;
	//private final int maxSessionTime = 20000;
	private User user;
	
	private StringProperty username;
	private StringProperty name;
	private StringProperty department;
	private StringProperty address;
	private StringProperty gender;
	private StringProperty email;
	private StringProperty telphone;
	private StringProperty group;		
	
	private UserSession() {
		this.username = new SimpleStringProperty();
		this.name = new SimpleStringProperty();
		this.department = new SimpleStringProperty();
		this.address = new SimpleStringProperty();
		this.gender = new SimpleStringProperty();
		this.email = new SimpleStringProperty();
		this.telphone = new SimpleStringProperty();
		this.group = new SimpleStringProperty();
	}

	/**
	 * 获取当前用户, 如果长时间未活动,则自动登出
	 * 
	 * @return
	 */
	public User getUser() {
		if (lastLoginTime < 0
				|| (System.currentTimeMillis() - lastLoginTime > maxSessionTime)) {
			if (user != null) {
				HessianFactoryManger.INSTANCE.getUserService().logout();
				user = null;
			}
		} else {
			updateUserActivity();
		}
		return user;
	}
	
	public void setUser(User user) {
		this.user = user;
		if (user != null) {
			
			username.setValue(user.getUsername());
			name.setValue(user.getName());
			department.setValue(user.getDepartment());
			address.setValue(user.getAddress());
			gender.setValue(user.getGender());
			email.setValue(user.getEmail());
			telphone.setValue(user.getTelphone());
			group.setValue(user.getGroup().getName());
			
			updateUserActivity();
		}
	}

	public void updateUserActivity() {
		log.debug("更新最后活动时间.");
		lastLoginTime = System.currentTimeMillis();
	}

	public StringProperty nameProperty() {
		return name;
	}

	public StringProperty usernameProperty() {
		return username;
	}

	public StringProperty departmentProperty() {
		return department;
	}

	public StringProperty addressProperty() {
		return address;
	}

	public StringProperty genderProperty() {
		return gender;
	}

	public StringProperty emailProperty() {
		return email;
	}

	public StringProperty telphoneProperty() {
		return telphone;
	}

	public StringProperty groupProperty() {
		return group;
	}

}
