import tables
cu = tables.cu

class AdminCmds:
	""" Special commands for admins."""

	def __init__(self, sessions, ipsessions):
		self.sessions = sessions
		self.ipsessions = ipsessions

	def do_addroom(self, session, line):
		try:
			cu.execute( "insert into rooms(\
						r_id, short_desc, long_desc, has_in, is_in)\
						values (NULL,'A room','Set the description.',NULL,NULL)")
			session.push("Your new room has id #")
			lastroom = cu.lastrowid
			session.push(str(lastroom) + "\r\n")
		except:
			session.push("Something didn't work.\r\n")

	def do_delroom(self, session, line):
		if line == '': session.push("Correct syntax:\r\ndelroom <room ID>\r\n")
		self.todest = line
		try:
			cu.execute("select r_id from rooms where r_id = %s", self.todest)
			fop = cu.fetchone()
		except:
			session.push("This room does not exist.\r\n")
		cu.execute("delete from rooms where r_id = %s", self.todest)
		self.msg = "Room #" + str(self.todest) + " has been destroyed.\r\n"
		session.push(self.msg)

	def do_listrooms(self, session, line):
		cu.execute("select r_id, short_desc from rooms")
		self.whole = cu.fetchall()
		self.title = "ID".ljust(6) + "SHORT DESC".ljust(15) + "\r\n"
		session.push(self.title)
		for i in self.whole:
			self.res = str(i[0]).ljust(6) + str(i[1]).ljust(15) + "\r\n"
			session.push(self.res)

	def do_addexit(self, session, line):
		self.argu = line
		if not self.argu.strip(): session.push("> ")
		parts = line.split(' ', 2)
		try: 
			fromroom = parts[0]
			toroom = parts[1]
			cu.execute( "insert into exits(exit_id, fromr, tor)\
						values (NULL, %s, %s)", parts[0], parts[1])
			self.firstext = cu.lastrowid
			cu.execute( "insert into exits(exit_id, fromr, tor)\
						values (NULL, %s, %s)", parts[1], parts[0])
			self.secext = cu.lastrowid
			self.msg = 'Exit #' + str(self.firstext) + ' for room #' +  str(parts[0]) + ' to room #' + str(parts[1])
			session.push(self.msg + "\r\n")
			self.msg = 'Exit #' + str(self.secext) + ' for room #' +  str(parts[1]) + ' to room #' + str(parts[0])
			session.push(self.msg + "\r\n")
		except: session.push("Correct syntax:\r\naddexit <room from> <room to>\r\n")

	def do_listexits(self, session, line):
		cu.execute("select exit_id,fromr,tor from exits")
		self.allex = cu.fetchall()
		#session.push("List of all exits:\r\n")
		self.title = "ID".ljust(6) + "FROM".ljust(6) + "TO".ljust(4) + "\r\n"
		session.push(self.title)
		for i in self.allex:
			self.exstr = str(i[0]).ljust(6) + str(i[1]).ljust(6) + str(i[2]).ljust(4)
			session.push(self.exstr + "\r\n")

	def do_delexit(self, session, line):
		if line == '': session.push("Correct syntax:\r\ndelexit <exit ID>\r\n")
		cu.execute("select exit_id from exits where exit_id = %s", line)
		self.barn = cu.fetchone()
		if self.barn != None: #If the object exists
			try:
				cu.execute("delete from exits where exit_id = %s", line)
				session.push("Exit #" + line + " has been destroyed.\r\n")
			except: session.push("This exit does not exists.\r\n")
		else: session.push("Exit ID not found.\r\n")

	def do_addlink(self, session, line):
		if line == '': session.push("Correct syntax:\r\naddlink <room ID> <exit ID> <direction>\r\n")
		self.argu = line.lower()
		if not self.argu.strip(): session.push("> ")
		parts = self.argu.split(' ', 3)
		try:
			roomnum = int(parts[0])
			exitnum = int(parts[1])
			direction = str(parts[2])
			cu.execute( "insert into links(room_id, exit, direction) values\
						(%s, %s, %s)", roomnum, exitnum, direction)
			session.push("New link added.\r\n")
		except:
			session.push("Correct syntax:\r\naddlink <room ID> <exit ID> <direction>\r\n")

	def do_listlinks(self, session, line):
		cu.execute("select * from links")
		self.linksall = cu.fetchall()
		self.title = "ROOM".ljust(6) + "EXIT".ljust(6) + "DIR".ljust(4) + "\r\n"
		session.push(self.title)

		for i in self.linksall:
			self.linkstr = str(i[0]).ljust(6) + str(i[1]).ljust(6) + str(i[2]).ljust(4)
			session.push(self.linkstr + "\r\n")

	def do_dellink(self, session, line):
		if line == '': session.push("Correct syntax:\r\ndellink <link ID>\r\n")
		self.todest = line.split(' ', 3)
		cu.execute("select * from links where room_id = %s and exit = %s", self.todest)
		self.linker = cu.fetchall()
		if self.linker != []:
			cu.execute("delete from links where room_id = %s and exit = %s", self.linker[0][0], self.linker[0][1])
			self.msg = "The link between Room #" + str(self.linker[0][0]) + " and Exit #" + str(self.linker[1]) + " by " + str(self.linker[2]) + " has been destroyed.\r\n"
			session.push(self.msg)
		else:
			session.push("This link does not exist.\r\n")

	def do_setshort(self, session, line):
		cu.execute("select is_in from pnames where p_id = %s", session.p_id)
		self.getloc = cu.fetchone()
		try:
			cu.execute("update rooms set short_desc = %s where r_id = %s", line, self.getloc[0])
			session.push("Short description changed.\r\n")
		except: session.push("This failed.\r\n")

	def do_setlong(self, session, line):
		cu.execute("select is_in from pnames where p_id = %s", session.p_id)
		self.getloc = cu.fetchone()
		try:
			cu.execute("update rooms set long_desc = %s where r_id = %s", line, self.getloc[0])
			session.push("Long description changed.\r\n")
		except: session.push("This failed.\r\n")

	def do_addhelp(self, session, line):
		if line == '': session.push("Correct syntax:\r\naddhelp <title> <documentation>\r\n")
		else:
			self.argu = line.lower()
			self.parts = self.argu.split(' ', 1)
			try:
				cu.execute("update helps set command = %s and doc = %s", self.parts[0], self.parts[2])
			except:
				cu.execute("insert into helps(command, doc) values\
					(%s, %s)", self.parts[0], self.parts[1])
			session.push("Help database updated.\r\n")

	def do_locate(self, session, line):
		cu.execute("select names,is_in,p_id,ip_addr from pnames where is_in > 0")
		self.all = cu.fetchall()

		self.title = "NAME".ljust(10) + "LOC".ljust(5) + "IP".ljust(4) + "\r\n"
		session.push(self.title)

		for i in self.all:
			self.msg = str(i[0]).ljust(10) +str(i[1]).ljust(5) + str(i[3]).ljust(4) +"\r\n"
			session.push(self.msg.capitalize())

	def do_goto(self, session, line):
		try:
			cu.execute("select short_desc,r_id from rooms where r_id = %s", line)
			self.exists = cu.fetchall()
			cu.execute("update pnames set is_in = %s where p_id = %s", self.exists[0][1], session.p_id)
			session.is_in = self.exists[0][1]
		except: session.push("You cannot go there.\r\n")

	def do_additem(self, session, line):
		if line == '': session.push("The object needs a name.\r\n")
		else:
			cu.execute("insert into objects(obj_id,name) values\
					(NULL, %s)", line.lower())
			session.push("Item " + line.lower() + " is created.\r\n")

	def do_listitems(self, session, line):
		cu.execute("select obj_id,name,description,flags from objects")
		self.lookobj = cu.fetchall()

		self.title = "ID".ljust(5) + "NAME".ljust(10) + "DESC".ljust(4) + "\r\n"
		session.push(self.title)

		for i in self.lookobj:
			session.push(str(i[0]).ljust(5) + str(i[1]).ljust(10) + str(i[2]).ljust(4) + "\r\n")

	def do_delitem(self, session, line):
		cu.execute("select obj_id from objects where obj_id = %s", line.lower())
		self.barn = cu.fetchone()
		if self.barn != None: #If the object exists
			cu.execute("delete from objects where obj_id = %s", line.lower())
			cu.execute("delete from instances where parent_id = %s", line.lower())
			session.push(line.lower() + " and all its instances have been destroyed.\r\n")
		else:
			session.push("This object does not exist.\r\n")

	def do_itemdesc(self, session, line):
		if line == '': session.push("> ")
		self.splitarg = line.split(' ', 1)
		cu.execute("select name from objects where name = %s", self.splitarg[0].lower())
		self.barn = cu.fetchone()
		if self.barn != None: #If the object exists
			cu.execute("update objects set description = %s where name = %s", self.splitarg[1], self.splitarg[0].lower())
			session.push("Description set on " + str(self.splitarg[0]).lower() + ".\n")
		else: session.push("Object does not exist.\r\n")

	def do_clone(self, session, line):
		try:
			cu.execute("select obj_id,name from objects where name = %s", line.lower())
			self.cloner = cu.fetchone()
			cu.execute("insert into instances(id,sub_id,parent_id,is_owned,is_in,npc_own) values\
						(NULL, 1, %s, %s, 0, 0)", self.cloner[0], session.p_id)
			session.push(str(self.cloner[1])+" has been cloned.\r\n")
		except: session.push("No such object.\r\n")

	def do_listinst(self, session, line):
		cu.execute("select id,sub_id,parent_id,is_owned,is_in,npc_own from instances")
		self.instobj = cu.fetchall()

		self.title = "ID".ljust(6) + "SUBID".ljust(6) + "PARENT".ljust(7) + "OWNED_BY".ljust(9) + "IS_IN".ljust(6) + "NPC".ljust(6) + "\r\n"
		session.push(self.title)

		for i in self.instobj:
			session.push(str(i[0]).ljust(6) + str(i[1]).ljust(6) + str(i[2]).ljust(7) + str(i[3]).ljust(9) + str(i[4]).ljust(6) + str(i[5]).ljust(6) + "\r\n")

	def do_dest(self, session, line):
		cu.execute("select id from instances where id = %s", line)
		self.barn = cu.fetchone()
		if self.barn != None: #If the instance exists, try:
			try:
				cu.execute("delete from instances where id = %s", line)
				session.push("Instance #" + line + " has been destroyed.\r\n")
			except: session.push("Instance " + line + " does not exist.\r\n")
		else: pass

	def do_addnpc(self, session, line):
		if line == '': session.push("The NPC needs a name.\r\n")
		else:
			cu.execute("insert into npcs(npc_id,name) values\
						(NULL, %s)", line.lower())
			session.push("NPC " + line.lower() + " created.\r\n")

	def do_npcdesc(self, session, line):
		if line == '': session.push("Correct syntax:\r\nnpcdesc <name> <description>\r\n")
		self.splitarg = line.split(' ', 1)
		cu.execute("select name from npcs where name = %s", self.splitarg[0].lower())
		self.barn = cu.fetchone()
		if self.barn != None: #If the object exists
			try:
				cu.execute("update npcs set description = %s where name = %s", self.splitarg[1], self.splitarg[0].lower())
				session.push("Description set on " + str(self.splitarg[0]).lower() + ".\n")
			except: session.push("This NPC does not exist.\r\n")
		else: pass

	def do_delnpc(self, session, line):
		cu.execute("select npc_id from npcs where npc_id = %s", line)
		self.barn = cu.fetchone()
		self.splitarg = line.split(' ', 1)
		if self.barn != None: #If the object exists
			try:
				cu.execute("delete from npcs where npc_id = %s", line)
				session.push("NPC #" + line + " had been destroyed.\r\n")
			except: session.push("This NPC does not exist.\r\n")
		else: pass

	def do_clonenpc(self, session, line):
		try:
			cu.execute("select npc_id,name from npcs where name = %s", line.lower())
			self.cloner = cu.fetchone()
			cu.execute("insert into instances(id,sub_id,parent_id,is_owned,is_in,npc_own) values\
						(NULL, 2, %s, 0, %s, 0)", self.cloner[0], session.is_in)
			session.push(str(self.cloner[1])+" cloned.\r\n")
		except: session.push("No such NPC.\r\n")

	def do_listnpcs(self, session, line):
		cu.execute("select npc_id,name,description from npcs")
		self.whole = cu.fetchall()

		self.title = "ID".ljust(5) + "NAME".ljust(10) + "DESC".ljust(6) + "\r\n"
		session.push(self.title)

		for i in self.whole:
			self.res = str(i[0]).ljust(5) + str(i[1]).ljust(10) + str(i[2]).ljust(6) + "\r\n"
			session.push(self.res)

	def do_listplayers(self, session, line):
		cu.execute("select p_id,names,email from pnames")
		self.allplay = cu.fetchall()

		self.title = "ID".ljust(5) + "NAME".ljust(15) + "EMAIL".ljust(20)+"\r\n"
		session.push(self.title)

		for i in self.allplay:
			self.playa = str(i[0]).ljust(5) + str(i[1].capitalize()).ljust(15) + str(i[2]).ljust(20) +"\r\n"
			session.push(self.playa)

	def do_ridplayer(self, session, line):
		cu.execute("select p_id,names from pnames where names = %s", line.lower())
		self.getrid = cu.fetchone()
		try:
			cu.execute("delete from pnames where names = %s", self.getrid[1])
			session.push("Player " + line.capitalize() + " has been wiped out of the database.\r\n")
		except:
			session.push("Player" + line.capitalize() + " not found in the database.\r\n")

	def do_edig(self, session, line):
		if line == '': session.push("> ")
		self.splitarg = line.split(' ', 1)

		cu.execute("select room_id,direction from links where room_id = %s", session.is_in)
		self.exists = cu.fetchall()
		self.twoway = {'north':'south','south':'north','up':'down','down':'up','northeast':'southwest','southwest':'northeast','northwest':'southeast','southeast':'northwest', 'east':'west', 'west':'east'}
		try:
			if self.exists[0][1] == self.splitarg[0]:
				session.push("This exit already exists here.\r\n")
			else:
				cu.execute("insert into rooms(r_id, short_desc, long_desc)\
							values(NULL,%s,'Set description.')", self.splitarg[1])
				cu.execute("select * from rooms")
				self.count = cu.rowcount
				cu.execute("insert into exits(exit_id,fromr,tor)\
							values(NULL,%s,%s)", session.is_in, self.count)
				cu.execute("insert into exits(exit_id,fromr,tor)\
							values(NULL,%s,%s)", self.count, session.is_in)
				cu.execute("select * from exits")
				self.firstex = cu.rowcount - 1
				self.secex = cu.rowcount
				cu.execute("insert into links(room_id,exit,direction)\
							values(%s,%s,%s)", session.is_in, self.firstex, self.splitarg[0])
				cu.execute("insert into links(room_id,exit,direction)\
							values(%s,%s,%s)", self.count, self.secex, self.twoway[self.splitarg[0]])
				session.push("New room created " + self.splitarg[0] + " of here.\r\n")
		except:
			session.push("Usage: dig <exit> <title/short description>\r\n")

	def do_addalias(self, session, line):
		if line == '': session.push("Correct syntax:\r\naddalias <name> <alias>\r\n")
		line = line.lower()
		self.splitarg = line.split(' ', 1)

		cu.execute("select obj_id,alias,name from objects where name = %s", self.splitarg[0])
		self.test = cu.fetchall()

		if self.test != []:
			try:
				if self.test[0][1] != None:
					self.add = self.test[0][1] + ":" + self.splitarg[1]
					cu.execute("update objects set alias = %s where name = %s", self.add, self.splitarg[0])
				else:
					cu.execute("update objects set alias = %s where name = %s", self.splitarg[1], self.splitarg[0])
			except: raise

	def do_email(self, session, line):
		if line == '': session.push("Correct syntax:\r\nemail <name>\r\n")
		line = line.lower()
		cu.execute("select names,email from pnames where names = %s", line)
		self.email = cu.fetchall()
		if self.email != []:
			session.push(str(self.email[0][0]) + ": " + str(self.email[0][1])+"\r\n")
		else:
			session.push("Player not found.\r\n")

#   do_logout() not available from here. Must find another way.
#	def do_kickout(self, session, line):
#		cu.execute("select p_id,names from pnames where names = %s", line.lower())
#		self.kicked = cu.fetchall()
#		self.do_logout(self, self.sessions[self.kicked[0][0]], line)