package com.eactive.eai.rms.client;

import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.mina.common.IoSession;
import org.apache.mina.common.IoSessionRecycler;

/**
 * The Class SimpleSessionRecycler.
 * 
 * <ul>
 * <li>1. Function : IoSession 의 Recycler </li>
 * <li>2. Summary :SessionRecycler에 의해 Session이 종료 되지 않고 접속 유지를
 * 하게 된다.</li>
 * <li>3. Notification :</li>
 * </ul>
 * 
 * @author  : $Author: 윤창용 $
 * @version : $Revision: 1.2 $
 */
public class SimpleSessionRecycler implements IoSessionRecycler {

	/** The recycle map. */
	Map<Object, IoSession> recycleMap = new HashMap<Object, IoSession>();

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.mina.common.IoSessionRecycler#remove(org.apache.mina.common.IoSession)
	 */
	public void remove(IoSession iosession) {
		recycleMap.remove(iosession);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.mina.common.IoSessionRecycler#recycle(java.net.SocketAddress,
	 *      java.net.SocketAddress)
	 */
	public IoSession recycle(SocketAddress localAddress,
			SocketAddress remoteAddress) {
		return (IoSession) recycleMap.get(generateKey(localAddress,
				remoteAddress));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.apache.mina.common.IoSessionRecycler#put(org.apache.mina.common.IoSession)
	 */
	public void put(IoSession iosession) {
		Object key = generateKey(iosession);
		if (!recycleMap.containsKey(key)) {
			recycleMap.put(key, iosession);
		}
	}

	/**
	 * Generate key.
	 * 
	 * @param iosession the iosession
	 * 
	 * @return the object
	 */
	private Object generateKey(IoSession iosession) {
		return generateKey(iosession.getLocalAddress(), iosession
				.getRemoteAddress());
	}

	/**
	 * Generate key.
	 * 
	 * @param localAddress the local address
	 * @param remoteAddress the remote address
	 * 
	 * @return the object
	 */
	private Object generateKey(SocketAddress localAddress,
			SocketAddress remoteAddress) {
		List<SocketAddress> key = new ArrayList<SocketAddress>(2);
		key.add(remoteAddress);
		key.add(localAddress);
		return key;
	}
}