/*
 * $Id: UserTrackingInfo.java,v 1.8 2007/10/30 12:23:12 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: UserTrackingInfo.java,v $
 * Revision 1.8  2007/10/30 12:23:12  marbobo
 * + removed unnecessary statements
 *
 * Revision 1.7  2006/04/29 18:39:49  marbobo
 * + Refactoriengs und eine Ausgaben vereinheitlicht
 *
 * Revision 1.6  2006/04/27 11:05:50  korowa
 * +getLastAccess() :neue Funktion hinzugefügt die den letzten Zugriffszeitpunkt des Benutzers liefert
 *
 * Revision 1.5  2004/07/20 08:51:39  jonyp
 * added copyright info + cvs log
 *
 *
 */
package vkc.view.bean;

import java.util.Date;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import vkc.db.serializer.VKCUserSerializer;
import vkc.exception.DBException;
import vkc.util.StringUtils;
import vkc.view.WebShare;
import vkc.misc.VKCLogManager;

public class UserTrackingInfo implements HttpSessionBindingListener {
	private Date loginDate = null;

	private HttpSession session = null;

	private Integer userId = new Integer(-1);

	private String ipAddress = "";
	private String realName = "";
	private String sessionId = "";

	private UserTrackingInfo() {
	}

	public UserTrackingInfo(Integer userId, String realname, HttpSession session, String ipAddress, Date loginDate) {
		this();
	    this.userId = userId;
		this.realName = realname;
		this.session = session;
		this.loginDate = loginDate;
		this.sessionId = StringUtils.normalize(session.getId());
		this.ipAddress = StringUtils.normalize(ipAddress);
	}

	public String getIpAddress() {
		return ipAddress;
	}

	public UserInfo getUserInfo() throws DBException {
		return VKCUserSerializer.retrieveUserInfo(getUserId());
	}

	public Date getLoginDate() {
		return loginDate;
	}

	public Integer getUserId() {
		return userId;
	}

	public String getSessionId() {
		return sessionId;
	}

	public HttpSession getSession() {
		return session;
	}

	public void valueBound(HttpSessionBindingEvent event) {
		WebShare.addActiveUser(this);
	}

	public void valueUnbound(HttpSessionBindingEvent event) {
		try {
			String log = "User '" + getUserInfo().getUsername()
					+ "' automatically logged out of session "
					+ getSessionId();

			VKCLogManager.infoLog(this, log);
		} catch (Exception e) {
		}

		WebShare.removeActiveUser(this);
	}

	public boolean equals(Object obj) {
		if (obj == null || obj instanceof UserTrackingInfo == false) {
			return false;
		}

		UserTrackingInfo bean = (UserTrackingInfo) obj;

		return bean.getSessionId().equals(getSessionId());
	}

	public String getRealName() {
		return realName;
	}

	public Date getLastAccess() {
		return new Date(getSession().getLastAccessedTime());
	}

	public String toString() {
		return getRealName() + " -> IP = " + getIpAddress();
	}
}