from javax.servlet.http import HttpServlet
from it.gotoandplay.smartfoxserver.webserver import WebHelper
from it.gotoandplay.smartfoxserver import SmartFoxServer
from sfs.cluster.lobby import DataStore


class ClusterAccess(HttpServlet):

	def __init__(self):
		self.htmlHead = "<html><head></head><body style='font-family:Verdana'>"
		self.closeHtml = "</body></html>"
		
		
	def doGet(self, request, response):	
		write = response.getWriter().println

		nodes = DataStore.instance().nodeUserCounts.entrySet()
		
		lowerCount = 99999999
		chosenServer = None
		
		for node in nodes:
			userCount = node.getValue().intValue()
			nodeName = node.getKey()
			portNumber = int(nodeName[nodeName.find(":") + 1])
			
			# filter only the lobby nodes (those that start with 9...)
			if portNumber == 9 and userCount < lowerCount:
				lowerCount = userCount 
				chosenServer = node.getKey()
			
		write(chosenServer)
		response.getWriter().close()
		
	#
	# Handles post requests
	#
	def doPost(self, request, response):	
		pass
		
	
		