package online.listener;

import java.io.Serializable;
import java.util.Optional;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Mutexリスナ
 *
 * @author Tadashi Nakayama
 */
public class SessionMutexListener implements HttpSessionListener {

	/** クラス名 */
	private static final String CLAZZ = SessionMutexListener.class.getName();

	/**
	 * @see javax.servlet.http.HttpSessionListener
	 * #sessionCreated(javax.servlet.http.HttpSessionEvent)
	 */
	@Override
	public void sessionCreated(final HttpSessionEvent se) {
		se.getSession().setAttribute(CLAZZ, new Mutex());
	}

	/**
	 * @see javax.servlet.http.HttpSessionListener
	 * #sessionDestroyed(javax.servlet.http.HttpSessionEvent)
	 */
	@Override
	public void sessionDestroyed(final HttpSessionEvent se) {
		se.getSession().removeAttribute(CLAZZ);
	}

	/**
	 * Mutex取得
	 *
	 * @param session セション
	 * @return Mutexオブジェクト
	 */
	public static Object getMutex(final HttpSession session) {
		final var ret = session.getAttribute(CLAZZ);
		return Optional.ofNullable(ret).orElse(session);
	}

	/**
	 * Mutex
	 *
	 * @author Tadashi Nakayama
	 */
	private static final class Mutex implements Serializable {
		/** serialVersionUID */
		private static final long serialVersionUID = 1L;

		/**
		 * コンストラクタ
		 */
		Mutex() {
			super();
		}
	}
}
