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 ClusterMonitor(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
		write(self.htmlHead)
		dataStore = DataStore.instance()
		
		usersByNode = self.getUsersByNode(dataStore.clusterUsersByName)
		
		write(("<h2 style='color:#ff2200; background-color:fffad0;padding:10px;border: 1px dashed #ccc'>Nodes in the cluster: %s </h2>" % (dataStore.nodeUserCounts.size())))
		
		for entry in dataStore.nodeUserCounts.entrySet():
			write("<b>" + entry.getKey() + "</b>: " + entry.getValue().toString() + " user(s) <hr size='1' noshade>")
		
			# get user list for this node
			userList = usersByNode.get(entry.getKey())
			
			if userList != None:
				write("<table cellpadding='4' cellspacing='1' border='0' style='margin-left:40px'>\n")
				write("<tr style='font-size:11px;color:#cc0000;font-weight:bold'><td>Name</td><td>Id</td><td>Friend List</td></tr>")
				for user in usersByNode.get(entry.getKey()):
					fList = self.getFriendList(user["name"])
					
					if fList:
						friends = ",".join(map(lambda friend: friend.name, fList))
					else:
						friends = "(empty)"
						
					html = "<tr style='font-size:11px;color:#444'>\n<td>%s</td><td>%s</td><td>%s</td></tr>" % (user["name"], user["id"], friends)
					write(html)
					
				write("</table>")
				
			write("<br>")
			
		write(self.closeHtml)
		
		response.getWriter().close()
		
	#
	# Handles post requests
	#
	def doPost(self, request, response):	
		pass
		
	#
	# Orders users by cluster node
	#
	def getUsersByNode(self, clusterUsersByName):
		usersByNode = {}
		
		for clusterUser in clusterUsersByName.values():
			if not usersByNode.has_key(clusterUser.nodeId):
				usersByNode[clusterUser.nodeId] = []
			
			usersByNode[clusterUser.nodeId].append({"id":clusterUser.localUID, "name":clusterUser.name})

		return usersByNode
	
	#
	# Grabs a list of users from the main friendListManager
	#
	def getFriendList(self, userName):
		zone = SmartFoxServer.getInstance().getZone("clusterLobby")
		friendListManager = zone.getExtension("clobby").getFriendListManager()
		return friendListManager.getFriendList(userName)
		