#!/usr/bin/python
# -*- coding: utf-8 -*-
from xml.dom import Node, minidom
global path, name

XML_GROUP = RM = 0
XML_SEL = ADD = 1
XML_NAME = 2
XML_ONLY = 3
XML_MODULE = 4
XML_SCREEN = 5
XML_CODE = 6
XML_ICON = 7
XML_INFO = 8
XML_KEY = 9

# stringToXML ---------------------------------------------------------------------------------------------------------------
def stringToXML(text):
	return text.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace("'", '&apos;').replace('"', '&quot;')

# gInstaller ---------------------------------------------------------------------------------------------------------------
class gInstaller(object):
	
	def __init__(self,doc=None):
		
		if doc:
			self.rootNode = doc.childNodes[0]
			self.list = []
			self.list = self.getDom()
		else:
			pass

	def getDom(self):
		list = []
		for node in self.rootNode.childNodes:
			if node.nodeType == Node.ELEMENT_NODE:
				for node2 in node.childNodes:
					if node2.nodeType == Node.ELEMENT_NODE:
						only = sel = name = module = screen = code = icon = info = key = ""
						for node3 in node2.childNodes:
							if node2.nodeType == Node.ELEMENT_NODE:
								for node4 in node3.childNodes:
									if node3.nodeType == Node.ELEMENT_NODE:
										if node4.nodeType == Node.TEXT_NODE or node4.nodeType == Node.CDATA_SECTION_NODE:
											if node3.nodeName == "sel":
												sel = node4.nodeValue.encode('utf-8')
											
											elif node3.nodeName == "name":
												name = node4.nodeValue.encode('utf-8')
										
											elif node3.nodeName == "only":
												only = node4.nodeValue.encode('utf-8')
										
											elif node3.nodeName == "module":
												module = node4.nodeValue.encode('utf-8')
											
											elif node3.nodeName == "screen":
												screen = node4.wholeText.encode('utf-8')
										
											elif node3.nodeName == "code":
												code = node4.wholeText.encode('utf-8')
										
											elif node3.nodeName == "icon":
												icon = node4.wholeText.encode('utf-8')
										
											elif node3.nodeName == "info":
												info = node4.wholeText.encode('utf-8')
										
											elif node3.nodeName == "key":
												key = node4.wholeText.encode('utf-8')
									
						group = node.nodeName.encode('utf-8')
						list.append((group, sel, name, only, module, screen, code, icon, info, key))
		return list
	
	def getList(self):
		return self.list
	
	def addEntry(self, p):
		self.list = self.getList()
		index = 0
		group_end = 0
		for x in self.list:
			index += 1
			if x[XML_SCREEN] == p[XML_SCREEN] and p[XML_SCREEN] != "":
				# print "[ginstall] exit"
				exit(0)
			if x[XML_CODE] == p[XML_CODE] and p[XML_CODE] != "":
				# print "[ginstall] exit"
				exit(0)
			if x[XML_GROUP] == p[XML_GROUP]:
				group_end = index
				
		if group_end:
			self.list.insert(group_end, (p[XML_GROUP], p[XML_SEL], p[XML_NAME], p[XML_ONLY], p[XML_MODULE], p[XML_SCREEN], p[XML_CODE], p[XML_ICON], p[XML_INFO], p[XML_KEY]))
		else:	
			self.list.append((p[XML_GROUP], p[XML_SEL], p[XML_NAME], p[XML_ONLY], p[XML_MODULE], p[XML_SCREEN], p[XML_CODE], p[XML_ICON], p[XML_INFO], p[XML_KEY]))
		self.saveToFile()
		
	def removeEntry(self, name, module, code):
		selection = []
		if self.list != []:
			for x in self.list:
				if x[XML_NAME] != "" and x[XML_NAME] == name:
					pass
				elif  x[XML_MODULE] != "" and x[XML_MODULE] == module:
					pass
				elif x[XML_CODE] != "" and x[XML_CODE] == code:
					pass
				else:
					selection.append((x))
					
			self.list = selection
			self.saveToFile()
		
	def Content(self, x):
		if x != None:
			xml = "\t\t<content>\n"
			xml += "\t\t\t<name><![CDATA[" + stringToXML(x[XML_NAME]) + "]]></name>\n"
			if x[XML_SEL] != "":
				xml += "\t\t\t<sel>1</sel>\n"
			if x[XML_MODULE] != "":
				xml += "\t\t\t<module>" + x[XML_MODULE] + "</module>\n"
			if x[XML_SCREEN] != "":
				xml += "\t\t\t<screen><![CDATA[" + x[XML_SCREEN] + "]]></screen>\n"
			if x[XML_CODE] != "":
				xml += "\t\t\t<code><![CDATA[" + x[XML_CODE] + "]]></code>\n"
			if x[XML_ICON] != "":
				xml += "\t\t\t<icon>" + x[XML_ICON] + "</icon>\n"
			if x[XML_INFO] != "":
				xml += "\t\t\t<info>" + x[XML_INFO] + "</info>\n"
			if x[XML_KEY] != "":
				xml += "\t\t\t<key>" + x[XML_KEY] + "</key>\n"
			xml += "\t\t</content>\n"
		return xml

	def saveToFile(self):
		xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"
		if self.list != []:
			group = self.list[0][XML_GROUP]
			xml += "<xml>\n\t<" + group + ">\n"
		
			for x in self.list:
				if group == x[XML_GROUP]:
					xml += self.Content(x)
				else:
					xml += "\t" + "</" + group + ">\n"
					group = x[XML_GROUP]
					xml += "\t" + "<" + group + ">\n"
					xml += self.Content(x)

			xml += "\t</" + group + ">\n</xml>\n"
			# path
		f = open(path, "w")
		f.write(xml)
		f.close()

# main ---------------------------------------------------------------------------------------------------------------
if __name__ == '__main__':
	import sys
	import os.path as os_path
	import xml.dom.minidom
	name = os_path.basename(sys.argv[0])
	for x in sys.argv:
		if x[0] == "(":
			try:
				exec("plugin = list(" + x + ")")
			except Exception, e:
				print "[" + name + "] " + str(e)
				sys.exit(1)
				
		if x[:5] == "path=":
			path = x[5:]
			if os_path.exists(path):
				pass
			else:
				print "[" + name + "] File not found"
				
		if x == "remove":
			cmd = RM
		if x == "add":
			cmd = ADD
		
	if len(sys.argv) == 1:
		print "Usage: " + name + "path=<filename> 'remove' (py tuple) or 'add' (py tuple),"
		sys.exit(1)
	try:
			doc = xml.dom.minidom.parse(path)
			XML_db = gInstaller(doc)
			if cmd == ADD:
				XML_db.addEntry(plugin)
			if cmd == RM:
				XML_db.removeEntry(plugin[XML_NAME], plugin[XML_MODULE], plugin[XML_CODE])
	except Exception, e:
		print "[" + name + "] " + str(e)

	sys.exit(0)
	