package com.yeejoin.amos.iec104.tcp.server.session;

import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;

import org.apache.log4j.Logger;

import io.netty.channel.ChannelHandlerContext;


public class SessionManager {

	private static ConcurrentHashMap<String, Session> Ipsessions = new ConcurrentHashMap<>();
	 
	private boolean isDebug = false;
	private volatile static SessionManager instance = null;
	ScheduledExecutorService service_session = null;
	
	private SessionManager() {}
	
    public static SessionManager getInstance(){
    	//先检查实例是否存在，如果不存在才进入下面的同步块
         if(instance == null){
        	 //同步块，线程安全的创建实例
             synchronized(SessionManager.class){
            	 //再次检查实例是否存在，如果不存在才真的创建实例
                 if(instance == null){
                     instance = new SessionManager();
                 }
             }
         }
         return instance;
    }

    /**
     * 	创建设备连接session
     */
	public Session createSession(ChannelHandlerContext ctx) {
		InetSocketAddress socket =  (InetSocketAddress) ctx.channel().remoteAddress();
		String key = socket.toString();
		if (!Ipsessions.containsKey(key)) {
			Session session = new Session(ctx);
			Ipsessions.put(key, session);
			session.refreshRecordTime();
			Logger.getLogger(this.getClass()).debug(key + " session created ");
			return session;
		}
		return null;
	}
	

	/**
	 * 	更新上次数据连接时间，如果session为空，则创建session
	 * @param sessionId
	 * @param ctx
	 */
	public void updateTimeStamp(ChannelHandlerContext ctx) {
		InetSocketAddress socket =  (InetSocketAddress) ctx.channel().remoteAddress();
		String key = socket.toString();
		Session session = Ipsessions.get(key);
		if (session != null) {
			session.refreshRecordTime();
		} else {
			createSession(ctx);
		}
	}
	
	/**
	 * 	移除session
	 * @param sessionId
	 */
	public void removeSession(ChannelHandlerContext ctx) {
		InetSocketAddress socket =  (InetSocketAddress) ctx.channel().remoteAddress();
		String key = socket.toString();
		Ipsessions.remove(key);
		Logger.getLogger(this.getClass()).debug(key + " session is removed ");
	}
	

	
	public boolean containsSession(ChannelHandlerContext ctx) {
		InetSocketAddress socket =  (InetSocketAddress) ctx.channel().remoteAddress();
		String key = socket.toString();
		return Ipsessions.containsKey(key);
	}
	
	public Session getSession(ChannelHandlerContext ctx) {
		InetSocketAddress socket =  (InetSocketAddress) ctx.channel().remoteAddress();
		String key = socket.toString();
		return Ipsessions.get(key);
	}


	public Collection<Session> getClients() {
		return Ipsessions.values();
	}

	public boolean isDebug() {
		return isDebug;
	}

	public void setDebug(boolean isDebug) {
		this.isDebug = isDebug;
	}
}
