package org.ros.chatto.logged;

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

import org.ros.chatto.model.UserSession;
import org.ros.chatto.service.UserService;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Getter
@Setter
@Slf4j
public class UserLoggingSessionListener implements HttpSessionBindingListener {

	private final String username;
	private final UserService userService;

	public UserLoggingSessionListener(String username) {
		this.username = username;
		userService = BeanUtil.getBean(UserService.class);
	}

	@Override
	public void valueBound(HttpSessionBindingEvent event) {

		UserLoggingSessionListener user = (UserLoggingSessionListener) event.getValue();

		log.debug("Incrementing session count for user {}", user.getUsername());

		userService.incrementUserSession(user.getUsername());

		// log.trace("Username = {} with sessions = {}", userSession.getUser(),
		// userSession.getNumSessions());
	}

	@Override
	public void valueUnbound(HttpSessionBindingEvent event) {
		UserLoggingSessionListener user = (UserLoggingSessionListener) event.getValue();

		log.debug("Decrementing session count for user {}", user.getUsername());

		UserSession userSession = userService
				.decrementUserSession(user.getUsername());

		log.trace("Username = {} with sessions = {}", userSession.getUser(),
				userSession.getNumSessions());

	}
}