package com.game.manager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.game.Global;
import com.game.data.Player;
import com.taurus.permanent.data.Session;

/**
 * 当前节点  玩家session管理类
 * 
 *
 */
public class SessionManager {

	private ConcurrentMap<Session, Player> sessionMap = null;

	public SessionManager() {
		this.sessionMap = new ConcurrentHashMap<Session, Player>();
	}

	/**
	 * 通过sessionid获取玩家
	 * @param sessionid
	 * @return
	 */
	public Player getPlayer(Session sessionid) {
		return this.sessionMap.get(sessionid);
	}

	/**
	 * 增加session
	 * @param sessionid
	 * @param player
	 */
	public void putPlayer(Session sessionid, Player player) {
		this.sessionMap.put(sessionid, player);
	}

	/**
	 * 删除session
	 * @param sessionid
	 */
	public Player deleteSession(Session sessionid) {
		if(sessionid == null)return null;
		sessionid.setHashId(null);
		Player player = this.getPlayer(sessionid);
		this.sessionMap.remove(sessionid);
		return player;
	}

	/**
	 * 当前服务器在线人数
	 * @return
	 */
	public int size() {
		return this.sessionMap.size();
	}
	
	public List<Player> getPlayerList(){
		List<Player> list = new ArrayList<Player>();
		list.addAll(sessionMap.values());
		return list;
	}

	/**
	 * 断线
	 * @param sender
	 */
	public synchronized void disconnect(Session sender) {
		Player player = this.deleteSession(sender);
		if (player == null) {
			return;
		}
		player.room.enqueueRunnable(new Runnable() {
			
			@Override
			public void run() {
				if (player.isDestroy)return;
				if (player.sender == sender) {
					player.isConnect = false;
					Global.gameCtr.playerNetState(player);
				}
			}
		});
	}

}
