Index: controlies/Server.py
===================================================================
--- controlies/Server.py	(revision 72)
+++ controlies/Server.py	(revision 73)
@@ -34,7 +34,8 @@
 
 # Start up the web service.     
 Root = MainLoop.ControlIESProtocol() #Resource object
-Root.PageDir='/home/manu/proyectos/controlies/www/'
+#Root.PageDir='/home/manu/proyectos/controlies/www/'
+Root.PageDir='/home/chisco/Proyectos/controlies/www'
 site = server.Site(Root)
 
 #my_server = static.File('/home/chisco/workspace/adminies/www/')
Index: controlies/Plugins/Hosts.py
===================================================================
--- controlies/Plugins/Hosts.py	(revision 72)
+++ controlies/Plugins/Hosts.py	(revision 73)
@@ -27,6 +27,7 @@
 import ldap
 import logging
 from math import ceil
+from operator import itemgetter
 
 class Hosts(object):
 
@@ -43,24 +44,46 @@
     def getName (self):
 		return self.mac	
 				
-    def validation(self):
+    def validation(self,action):
+
+		if action == "add":
+			if self.type == "none":
+				return "type"
+		
 		if self.name == "":
 			return "name"
+			
+		if self.type <> 'thinclient':
+			if self.ip == "":
+				return "ip"
 
-		if self.ip == "":
-			return "ip"
-			
 		if self.mac == "":
 			return "mac"
-			
+
 		if self.type == "":
 			return "type"
 		
-		return "OK"
+		if action == "add":
+			if self.existsHostname():
+				return "hostAlreadyExists"
+		
+			# thinclients no requieren ip, la cogen dinamicamente en el aula
+			if self.type <> "thinclient":
+				if self.existsIP():
+					return "ipAlreadyExists"
 
+			if self.existsMAC():
+				return "macAlreadyExists"
+
+		elif action == "modify":			
+			return "OK"
+
+		return "OK"		
+		
     def process(self,action):
+		import pdb
 		if action == "add":
-			val = self.validation()
+			val = self.validation(action)
 			
 			if val != "OK":
 				return val
@@ -87,48 +110,163 @@
 			
     def list(self,args):
 		
-		#Distinguimos entre hosts ltsp, workstations y portatiles
-		print "Estoy en Hosts.py"
+		#from Plugins.LdapConnection import LdapConnection
+
+		#l = LdapConnection("172.23.36.5",'cn=admin,ou=People,dc=instituto,dc=extremadura,dc=es',"Sta1987teleco")
+		#l.connect()
+		
+		# grid parameters
 		limit = int(args['rows'][0])
 		page = int(args['page'][0])
+		start = limit * page - limit
+		finish = start + limit;				
+
+		# sort by field
+		sortBy = args['sidx'][0]
+		#if sortBy == "uid":
+			#sortBy = "id"
+
+		# reverse Sort
+		reverseSort = False
+		if args['sord'][0] == "asc":
+			reverseSort = True
+		
+		#Distinguimos entre hosts ltsp, workstations y portatiles
 		type = args['type'][0]
 		
-		if type == "LTSP":
-			search = self.ldap.search("ou=hosts","cn=*",["cn","ipHostNumber","macAddress"])
-		elif type == "thinClient":
-			search = self.ldap.search("ou=hosts","cn=*",["cn","ipHostNumber","macAddress"])	
+						
+		if type == "ltsp":
+			# Obtengo todos los elementos del nodo hosts
+			#search = l.search("ou=hosts","cn=*",["cn","ipHostNumber","macAddress"])
+			#filter = self.buildFilter(args)		
+			search = self.ldap.search("ou=hosts","cn=*",["cn","ipHostNumber","macAddress"])		
 			
-		start = limit * page - limit
-		finish = start + limit;		
+			# triplets que contiene los nombres de los ltsp-servers
+			#triplets = l.search("ou=Netgroup","cn=ltsp-server-hosts",["nisNetgroupTriple"])
+			triplets = self.ldap.search("ou=Netgroup","cn=ltsp-server-hosts",["nisNetgroupTriple"])
+			triplets = triplets [0][0][1]["nisNetgroupTriple"]
+			hostnames=list()
+			
+			for node in triplets:
+				name = node.replace(",-,-)","").replace("(","")
+				hostnames.append(name)
+				
+			# Ahora tengo que quedarme con los elementos de search que estan en hostnames: los que son ltsp
+			resultado=list()
+			for element in search:
+				if element[0][1]["cn"][0] in hostnames:
+					resultado.append(element)
+			
+			search = resultado 
+
+			if len(search) > 0:
+				totalPages = ceil( len(search) / int(limit) )
+			else:
+				totalPages = 0
+			if page > totalPages:
+				page = totalPages
+				
+			rows = []
+			for i in search[start:finish]:
+				row = {
+					"id":i[0][1]["cn"][0], 
+					"cell":[i[0][1]["cn"][0], i[0][1]["ipHostNumber"][0],i[0][1]["macAddress"]],
+					"cn":i[0][1]["cn"][0],
+					"ipHostNumber":i[0][1]["ipHostNumber"][0],
+					"macAddress":i[0][1]["macAddress"][0]
+				}				
+				#row = { "cn":i[0][0], "cell":[i[0][1]["cn"][0], i[0][1]["ipHostNumber"][0],i[0][1]["macAddress"]]}
+				rows.append(row)
+				
+			result = sorted(rows, key=itemgetter(sortBy), reverse=reverseSort)
+			return { "page":page, "total":totalPages, "records":len(search), "rows":result  }		
+				
+		elif type == "thinclient":
+			#import pdb
+			#search = l.search("cn=THINCLIENTS,cn=DHCP Config", "cn=*",["cn","dhcpHWAddress"])
+			search = self.ldap.search("cn=THINCLIENTS,cn=DHCP Config","cn=*",["cn","dhcpHWAddress"])		
+			#search[6][0][1]["cn"][0]
+			
+			if len(search) > 0:
+				totalPages = ceil( len(search) / int(limit) )
+			else:
+				totalPages = 0
+			if page > totalPages:
+				page = totalPages
+				
+			rows = []
+			# esto hay que cambiarlo: tenemos 4 groups en thinclientes
+			for i in search[6:finish]:
+					row = {
+						"id":i[0][1]["cn"][0], 
+						"cell":[i[0][1]["cn"][0], i[0][1]["dhcpHWAddress"]],
+						"cn":i[0][1]["cn"][0],
+						"dhcpHWAddress":i[0][1]["dhcpHWAddress"][0]
+					}						
+					#row = { "cn":i[0][0], "cell":[i[0][1]["cn"][0], i[0][1]["dhcpHWAddress"][0]]}
+					rows.append(row)
+
+			result = sorted(rows, key=itemgetter(sortBy), reverse=reverseSort)
+			return { "page":page, "total":totalPages, "records":len(search), "rows":result }					
 		
-		if len(search) > 0:
-			totalPages = ceil( len(search) / int(limit) )
-		else:
-			totalPages = 0
+		elif type == "workstation":
+			# Obtengo todos los elementos del nodo hosts
+			#search = l.search("ou=hosts","cn=*",["cn","ipHostNumber","macAddress"])
+			search = self.ldap.search("ou=hosts","cn=*",["cn","ipHostNumber","macAddress"])					
+			# triplets que contiene los nombres de las workstations
+			#triplets = l.search("ou=Netgroup","cn=workstation-hosts",["nisNetgroupTriple"])
+			triplets = self.ldap.search("ou=Netgroup","cn=workstation-hosts",["nisNetgroupTriple"])
+			triplets = triplets [0][0][1]["nisNetgroupTriple"]
+			hostnames=list()
+			
+			# obtengo lista de nombres de los hosts workstation
+			for node in triplets:
+				name = node.replace(",-,-)","").replace("(","")
+				hostnames.append(name)
+				
+			# Ahora tengo que quedarme con los elementos de search que estan en hostnames
+			resultado=list()
+			for element in search:
+				if element[0][1]["cn"][0] in hostnames:
+					resultado.append(element)
+			
+			search = resultado 
 
-		if page > totalPages:
-			page = totalPages
-		# print search[0][0][1]["uidNumber"][0]
-		rows = []
-		for i in search[start:finish]:
-			row = { "cn":i[0][0], "cell":[i[0][1]["cn"][0], i[0][1]["ipHostNumber"][0],i[0][1]["macAddress"]]}
-			rows.append(row)
+			if len(search) > 0:
+				totalPages = ceil( len(search) / int(limit) )
+			else:
+				totalPages = 0
+			if page > totalPages:
+				page = totalPages					
+		
+			rows = []
+			for i in search[start:finish]:
+				row = {
+					"id":i[0][1]["cn"][0], 
+					"cell":[i[0][1]["cn"][0], i[0][1]["ipHostNumber"][0],i[0][1]["macAddress"]],
+					"cn":i[0][1]["cn"][0],
+					"ipHostNumber":i[0][1]["ipHostNumber"][0],
+					"macAddress":i[0][1]["macAddress"][0]
+				}						
+				#row = { "cn":i[0][0], "cell":[i[0][1]["cn"][0], i[0][1]["ipHostNumber"][0],i[0][1]["macAddress"]]}
+				rows.append(row)
 
-		return { "page":page, "total":totalPages, "records":len(search), "rows":rows }
+			result = sorted(rows, key=itemgetter(sortBy), reverse=reverseSort)
+			return { "page":page, "total":totalPages, "records":len(search), "rows":result }		
 
     def add(self):
-		record = [
-		('objectclass', ['person','organizationalperson','inetorgperson']),
-		('uid', ['francis']),
-		('cn', [self.name] ),
-		('sn', ['Bacon'] ),
-		('userpassword', [self.password]),
-		('ou', ['users'])
-		]
-		try:
-			self.ldap.add("cn=hosts", record)
-		except ldap.ALREADY_EXISTS:
-			return "fail"
+		#record = [
+		#('objectclass', ['person','organizationalperson','inetorgperson']),
+		#('uid', ['francis']),
+		#('cn', [self.name] ),
+		#('sn', ['Bacon'] ),
+		#('userpassword', [self.password]),
+		#('ou', ['users'])
+		#]
+		#try:
+		#	self.ldap.add("cn=hosts", record)
+		#except ldap.ALREADY_EXISTS:
+		#	return "fail"
 		
 		return "OK"
  
@@ -147,7 +285,54 @@
 		from twisted.internet import defer
 		from Plugins import NetworkUtils
 		NetworkUtils.startup(self.mac)
+		
+		
+    def existsHostname(self):
+	
+		if self.type == 'thinclient':
+			result = self.ldap.search("ou=hosts","cn="+self.name,["cn"])
+		else:
+			result = self.ldap.search("ou=hosts","cn="+self.name,["cn"])
+		
+		if len(result) > 0:
+			return True
+		
+		return False
+		
+    def existsMAC(self):
+		import pdb
+		# Compruebo con las macs de la rama hosts
+		pdb.set_trace()
+		if self.type == 'thinclient':
+			search = self.ldap.search("cn=THINCLIENTS,cn=DHCP Config","cn=a*",["dhcpHWAddress"])
+			
+			#print search [0][0][1]['dhcpHWAddress'][0]
 
+			pdb.set_trace()
+			result = self.ldap.search("ou=hosts","macAddress="+self.mac,["macAddress"])
+		else:
+			result = self.ldap.search("ou=hosts","macAddress="+self.mac,["macAddress"])
+
+		if len(result) > 0:
+			return True
+		
+		return False
+		
+    def existsIP (self):
+		# Cojo las ips de la rama hosts -> arpa -> in-addr
+		result = self.ldap.search ("dc=23,dc=172,dc=in-addr,dc=arpa,ou=hosts", "dc=*",["associatedDomain"])
+		
+		myIP = self.ip.split (".")
+
+		for i in range (0, len (result) -1):
+			reverseIP = result [i][0][1]['associatedDomain'][0].replace (".in-addr.arpa","").split(".")
+			reverseIP.reverse() 
+			if myIP == reverseIP:
+				return True
+		
+		return False
+		
+
 #	def wakeup(self):
 #		from twisted.internet.task import LoopingCall
 #		from twisted.internet import defer
Index: controlies/www/ltsp/index.html
===================================================================
--- controlies/www/ltsp/index.html	(revision 72)
+++ controlies/www/ltsp/index.html	(revision 73)
@@ -40,7 +40,7 @@
 					caption: "Insertar",
 					buttonicon :'ui-icon-plus',
 					onClickButton : function (){ 
-						handleRecord('add','Añadir Usuario');
+						addRecord();
 					} 
 				}); 
 				$("#list").jqGrid('navButtonAdd','#pager',{
@@ -124,6 +124,25 @@
 					}
 				}).dialog('open');
 			}
+			
+			function addRecord(){
+
+				$("#dialog-form").html("");
+				$("#dialog-form").load("ltsp/form.html", function() {
+					$("#form_data #action").val("add");
+					$("#form_data #messageForm").html("Todos los campos son obligatorios");					
+				});
+
+				x = ($(window).width()-250)/2;
+				y = ($(window).height()-400)/2;
+
+				$("#dialog-form").dialog({
+					resizable: false,
+					position: top,
+					modal: true,
+					title: "Añadir Servidor de Aula (ltsp)"
+				}).dialog('option', 'position', [x, y]);
+			}					
 		</script>
 
 		<div id="tabla_clientes">
Index: controlies/www/thinclients/index.html
===================================================================
--- controlies/www/thinclients/index.html	(revision 72)
+++ controlies/www/thinclients/index.html	(revision 73)
@@ -39,7 +39,7 @@
 					caption: "Insertar",
 					buttonicon :'ui-icon-plus',
 					onClickButton : function (){ 
-						handleRecord('add','Añadir Usuario');
+						addRecord();
 					} 
 				}); 
 				$("#list").jqGrid('navButtonAdd','#pager',{
@@ -123,6 +123,25 @@
 					}
 				}).dialog('open');
 			}
+			
+			function addRecord(){
+
+				$("#dialog-form").html("");
+				$("#dialog-form").load("thinclients/form.html", function() {
+					$("#form_data #action").val("add");
+					$("#form_data #messageForm").html("Todos los campos son obligatorios");					
+				});
+
+				x = ($(window).width()-250)/2;
+				y = ($(window).height()-400)/2;
+
+				$("#dialog-form").dialog({
+					resizable: false,
+					position: top,
+					modal: true,
+					title: "Añadir Cliente Ligero"
+				}).dialog('option', 'position', [x, y]);
+			}							
 		</script>
 
 		<div id="tabla_clientes">
Index: controlies/www/workstation/index.html
===================================================================
--- controlies/www/workstation/index.html	(revision 72)
+++ controlies/www/workstation/index.html	(revision 73)
@@ -39,8 +39,8 @@
 				$("#list").jqGrid('navButtonAdd','#pager',{
 					caption: "Insertar",
 					buttonicon :'ui-icon-plus',
-					onClickButton : function (){ 
-						handleRecord('add','Añadir Usuario');
+					onClickButton :  function (){ 
+						addRecord();
 					} 
 				}); 
 				$("#list").jqGrid('navButtonAdd','#pager',{
@@ -47,7 +47,7 @@
 					caption: "Modificar", 
 					buttonicon :'ui-icon-pencil',
 					onClickButton : function (){ 
-						handleRecord('modify','Modificar Usuario');
+						modifyRecord();
 					} 
 				}); 
 				$("#list").jqGrid('navButtonAdd','#pager',{
@@ -60,10 +60,17 @@
 
 				$("#list").jqGrid('filterToolbar'); 
 			}
+
+			function modifyRecord(){
+				var uid;
+				
+				var uid = rowSelected();
+				
+			}
 			
 			function rowSelected(){
 				var id = $("#list").jqGrid('getGridParam','selrow'); 
-
+				alert (id);
 				if( id == null ){
 					$( "#dialog-alert" ).dialog({
 						resizable: false,
@@ -124,6 +131,26 @@
 					}
 				}).dialog('open');
 			}
+			
+			function addRecord(){
+
+				$("#dialog-form").html("");
+				$("#dialog-form").load("workstation/form.html", function() {
+					$("#form_data #action").val("add");
+					$("#form_data #messageForm").html("Todos los campos son obligatorios");					
+				});
+
+				x = ($(window).width()-250)/2;
+				y = ($(window).height()-400)/2;
+
+				$("#dialog-form").dialog({
+					resizable: false,
+					position: top,
+					modal: true,
+					title: "Añadir Workstation"
+				}).dialog('option', 'position', [x, y]);
+			}			
+			
 		</script>
 
 		<div id="tabla_clientes">
Index: controlies/MainLoop.py
===================================================================
--- controlies/MainLoop.py	(revision 72)
+++ controlies/MainLoop.py	(revision 73)
@@ -101,7 +101,6 @@
         	return json.dumps({"connection" : response})
         	
         if command == "users":
-        	
         	from Plugins.Users import Users
 
         	if request.args['action'][0] == "list":
@@ -142,7 +141,6 @@
 					classrooms = request.args['multiselect_classrooms']
 				except:
 					pass
-
 				u = Users(l,request.args['type'][0],request.args['name'][0],request.args['surname'][0],request.args['nif'][0],request.args['user'][0],request.args['password'][0],request.args['password2'][0],departments,classrooms)
 				response = u.process(request.args['action'][0])
 				return json.dumps({"response" : response})
@@ -176,7 +174,7 @@
         if command == "hosts":
 			
         	from Plugins.Hosts import Hosts
-        	
+
         	if request.args['action'][0] == "list":
 				h = Hosts (l,"","","","")
 				response = h.list(request.args)
@@ -187,8 +185,11 @@
 				#h.wakeup()
 				return json.dumps(response)
         	else:
-				h = Hosts(l,request.args['name'][0],request.args['ip'][0],request.args['mac'][0])
-				print request.args['name'][0]
+				if request.args ['type'][0] == 'thinclient':
+					ip = ""
+				else:
+					ip = request.args ['ip'][0]
+				h = Hosts(l,request.args['name'][0],ip,request.args['mac'][0],request.args['type'][0])
 				response = h.process(request.args['action'][0])
 				return json.dumps({"response" : response})
 				
