from qt import *
from xml.dom.minidom import Document, Node, parse
import string

############################################################################################################################################
#                                               IrcClientOptionsDialog                            
############################################################################################################################################

TRUE = 1
FALSE = 0

class IrcClientOptionsDialog(QDialog):
	def __init__ (self, parent):
		QDialog.__init__(self, parent,"",TRUE, Qt.WStyle_Customize|Qt.WStyle_NoBorderEx|Qt.WStyle_Title)

		self.parent = parent

		self.serverNameString = ""
		self.serverPortString = ""
		
		self.setCaption("Qt ProgXRC - Options")
     
		self.baseGridLayout = QGridLayout(self, 5, 5)
		self.baseGridLayout.addColSpacing(0,10)
		self.baseGridLayout.addColSpacing(2,20)
		self.baseGridLayout.addColSpacing(4,10)
		self.baseGridLayout.addRowSpacing(0,10)
		self.baseGridLayout.addRowSpacing(2,20)
		self.baseGridLayout.addRowSpacing(4,10)
                
		self.downLeftGridLayout = QGridLayout(9,3)
		self.downLeftGridLayout.addRowSpacing(1,10)
		self.downLeftGridLayout.addRowSpacing(3,30)
		self.downLeftGridLayout.addRowSpacing(5,10)
		self.downLeftGridLayout.addRowSpacing(7,10)
		
		self.logCheckBox = QCheckBox("Save logs", self)
		self.downLeftGridLayout.addWidget(self.logCheckBox, 0,0)		
		
		self.defaultConnectionCheckBox = QCheckBox("Auto connect", self)
		self.downLeftGridLayout.addWidget(self.defaultConnectionCheckBox, 2,0)
		
		self.toDefault = QLabel("to Default",self)
		self.downLeftGridLayout.addWidget(self.toDefault, 2,2, Qt.AlignLeft)
		
		self.NickLabel = QLabel("Nick : ", self)
		self.nick = QLineEdit(self)
				
		self.downLeftGridLayout.addWidget(self.NickLabel,4,0)
		self.downLeftGridLayout.addWidget(self.nick,4,2)
		
		self.fullNameLabel = QLabel("Full name : ", self)
		self.fullName = QLineEdit(self)
				
		self.downLeftGridLayout.addWidget(self.fullNameLabel,6,0)
		self.downLeftGridLayout.addWidget(self.fullName,6,2)
		
		self.userNameLabel = QLabel("User name : ", self)
		self.userName = QLineEdit(self)
				
		self.downLeftGridLayout.addWidget(self.userNameLabel,8,0)
		self.downLeftGridLayout.addWidget(self.userName,8,2)		
		
		self.baseGridLayout.addLayout(self.downLeftGridLayout,3,1)
		
		self.serverListView = QListView(self)
		self.serverListView.setHScrollBarMode(QScrollView.AlwaysOn)
		self.serverListView.setVScrollBarMode(QScrollView.AlwaysOn)
		
                
		self.serverListView.addColumn("Server name",122)
		self.serverListView.addColumn("Port")
		self.serverListView.setAllColumnsShowFocus(TRUE)
		#self.serverListView.setShowSortIndicator(TRUE) #PB QD CLASSE PAR N° PORT
		self.connect(self.serverListView, SIGNAL("selectionChanged(QListViewItem*)"), self.onServerListViewClicked)
		#QListViewItem(self.serverListView, "irc.epiknet.org", "6667")
		#QListViewItem(self.serverListView, "irc.epiknet.org (default)", "6667")
		#QListViewItem(self.serverListView, "irc.epiknet(default).org", "6667")
		
		self.loadOptions()
		
		self.baseGridLayout.addWidget(self.serverListView,1,1)
				
		self.upRightGridLayout = QGridLayout(5,1)
		self.upRightGridLayout.addRowSpacing(1,5)
		self.upRightGridLayout.addRowSpacing(3,5)
		self.upRightGridLayout.setRowStretch(0,1)
		self.upRightGridLayout.setRowStretch(4,1)
				
		self.addButton = QPushButton("Add",self)
		self.addButton.setMaximumSize(60,25)
		self.upRightGridLayout.addWidget(self.addButton, 0,0,Qt.AlignHCenter|Qt.AlignBottom)
		self.connect(self.addButton, SIGNAL("clicked()"), self.onAdd)
		
		self.delButton = QPushButton("Delete",self)
		self.delButton.setMaximumSize(60,25)
		self.delButton.setEnabled(FALSE)
		self.upRightGridLayout.addWidget(self.delButton, 2,0,Qt.AlignCenter)
		self.connect(self.delButton, SIGNAL("clicked()"), self.onDelete)
		
		self.defaultButton = QPushButton("Default",self)
		#self.addButton.width(),self.addButton.height())
		self.defaultButton.setMaximumSize(60,25)
		self.defaultButton.setEnabled(FALSE)
		#self.defaultButton.setMaximumSize(self.delButton.width(),self.delButton.height())
		self.upRightGridLayout.addWidget(self.defaultButton, 4,0,Qt.AlignHCenter|Qt.AlignTop)
		self.connect(self.defaultButton, SIGNAL("clicked()"), self.onDefault)
		
		self.baseGridLayout.addLayout(self.upRightGridLayout,1,3)
		
		self.downRightGridLayout = QGridLayout(3,1)
		self.downRightGridLayout.addRowSpacing(1,5)
		self.downRightGridLayout.setRowStretch(0,1)
		#self.downRightGridLayout.setRowStretch(2,1)
		
		self.cancelButton = QPushButton("Cancel",self)
		self.cancelButton.setMaximumSize(60,25)
		self.connect(self.cancelButton, SIGNAL("clicked()"), self.onCancel)
		self.downRightGridLayout.addWidget(self.cancelButton,0,0, Qt.AlignHCenter|Qt.AlignBottom)
		
		self.okButton = QPushButton("OK", self)
		self.okButton.setMaximumSize(60,25)
		self.connect(self.okButton, SIGNAL("clicked()"), self.onOk)
		self.downRightGridLayout.addWidget(self.okButton,2,0,Qt.AlignHCenter|Qt.AlignTop)
		    
		self.baseGridLayout.addLayout(self.downRightGridLayout,3,3)
		
		       
		self.show()
		
	def loadOptions(self):
		
		self.configList = { }
		xmldoc = parse("options.xml")
		for n in xmldoc.documentElement.childNodes:
			if(n.nodeName == "serverlist"):
				for i in n.childNodes:
					if i.nodeType == Node.ELEMENT_NODE:
						value = string.strip(i.getElementsByTagName("server-name").item(0).firstChild.nodeValue)
						if(i.attributes["default"].value == "true"):
							self.xmlTempServerName = value + " (default)"
						else:
							self.xmlTempServerName = value
						self.xmlTempServerPort = string.strip(i.getElementsByTagName("server-port").item(0).firstChild.nodeValue)

						QListViewItem(self.serverListView, self.xmlTempServerName, self.xmlTempServerPort)

			if(n.nodeName == "logs"):
				if(n.attributes["state"].value == "true"):
					self.logCheckBox.setChecked(TRUE)
				else:
					self.logCheckBox.setChecked(FALSE)

			if(n.nodeName == "auto-connect"):
				if(n.attributes["state"].value == "true"):
					self.defaultConnectionCheckBox.setChecked(TRUE)
				else:
					self.defaultConnectionCheckBox.setChecked(FALSE)

			if(n.nodeName == "user"):
					self.configList["nick"] = string.strip(n.getElementsByTagName("nick").item(0).firstChild.nodeValue)
					self.configList["full-name"] = string.strip(n.getElementsByTagName("full-name").item(0).firstChild.nodeValue)
					self.configList["user-name"] = string.strip(n.getElementsByTagName("user-name").item(0).firstChild.nodeValue)
			
		self.nick.setText(self.configList["nick"])
		self.fullName.setText(self.configList["full-name"])
		self.userName.setText(self.configList["user-name"])
		
	def saveOptions(self):
		xmldoc = Document()
		xmltag = xmldoc.createElement("options")
		
		self.xmlServerListTag = xmldoc.createElement("serverlist")
			
		i = self.serverListView.childCount()
		self.currentItem = self.serverListView.firstChild()
		while i>0:
			self.xmlTempServer = xmldoc.createElement("server")
			
			if((self.currentItem.text(0)).contains(" (default)") == 1):
				self.serverAttribute = "true"
				self.tempServerName = self.currentItem.text(0)
				self.tempServerName.truncate(self.tempServerName.find(" (default)"))
				self.currentItem.setText(0,self.tempServerName.latin1())
			else:
				self.serverAttribute = "false"
			
			self.xmlTempServer.setAttribute("default",self.serverAttribute)
			
			self.xmlTempServerName = xmldoc.createElement("server-name")
			self.xmlTempServerName.appendChild(xmldoc.createTextNode(self.currentItem.text(0).latin1()))
			self.xmlTempServerPort = xmldoc.createElement("server-port")
			self.xmlTempServerPort.appendChild(xmldoc.createTextNode(self.currentItem.text(1).latin1()))
			
			self.xmlTempServer.appendChild(self.xmlTempServerName)
			self.xmlTempServer.appendChild(self.xmlTempServerPort)
			
			self.xmlServerListTag.appendChild(self.xmlTempServer)
			
			self.currentItem = self.currentItem.itemBelow()
			i = i-1
			
		xmltag.appendChild(self.xmlServerListTag)
		
		self.xmlLogTag = xmldoc.createElement("logs")
		if(self.logCheckBox.isChecked()):
			self.xmlLogTag.setAttribute("state","true")
		else:
			self.xmlLogTag.setAttribute("state","false")
		
		xmltag.appendChild(self.xmlLogTag)
		
		self.xmlAutoConnectTag = xmldoc.createElement("auto-connect")
		if(self.defaultConnectionCheckBox.isChecked()):
			self.xmlAutoConnectTag.setAttribute("state", "true")
		else:
			self.xmlAutoConnectTag.setAttribute("state", "false")
				
		xmltag.appendChild(self.xmlAutoConnectTag)				

		self.xmlUserTag = xmldoc.createElement("user")
		
		self.xmlNickTag = xmldoc.createElement("nick")
		self.xmlNickTag.appendChild(xmldoc.createTextNode(self.nick.text().latin1()))
		self.xmlFullNameTag = xmldoc.createElement("full-name")
		self.xmlFullNameTag.appendChild(xmldoc.createTextNode(self.fullName.text().latin1()))
		self.xmlUserNameTag = xmldoc.createElement("user-name")
		self.xmlUserNameTag.appendChild(xmldoc.createTextNode(self.userName.text().latin1()))
		
		self.xmlUserTag.appendChild(self.xmlNickTag)
		self.xmlUserTag.appendChild(self.xmlFullNameTag)
		self.xmlUserTag.appendChild(self.xmlUserNameTag)
		
		xmltag.appendChild(self.xmlUserTag)		
		
		xmldoc.appendChild(xmltag)
		
		xmlFile = open("options.xml", "w")
		xmldoc.encoding = "ISO-8859-1"
		xmldoc.actualEncoding = "ISO-8859-1"
		xmlFile.write(xmldoc.toprettyxml().replace("""<?xml version="1.0" ?>""", """<?xml version="1.0" encoding="ISO-8859-1"?>"""))
		xmlFile.close()
		xmldoc.unlink()

	def setServerNameString(self, stringToSet):
		self.serverNameString = stringToSet
		
	def setServerPortString(self, stringToSet):
		self.serverPortString = stringToSet
		
	def onServerListViewClicked(self):
		
		if(self.serverListView.selectedItem().text(0).contains(" (default)")== FALSE):
			self.defaultButton.setEnabled(TRUE)
			self.delButton.setEnabled(TRUE)
		else:
			self.defaultButton.setEnabled(FALSE)
			self.delButton.setEnabled(FALSE)
		
	def onAdd(self):
		self.addDialog = ServerDialog(self, "Qt ProgXRC - Add Server")
		if self.serverNameString.latin1() != "":
			self.serverToAddItem = QListViewItem(self.serverListView, self.serverNameString, self.serverPortString)
			
	def onDelete(self):
		self.serverListView.takeItem(self.serverListView.selectedItem())
		
		#if self.serverListView.selectedItem() == None:
		self.delButton.setEnabled(FALSE)
		self.defaultButton.setEnabled(FALSE)
		
	def onDefault(self):
		self.newDefault = self.serverListView.selectedItem()
		i = self.serverListView.childCount()
		self.currentItem = self.serverListView.firstChild()
		
		while ( (i>0) and (self.currentItem.text(0).contains(" (default)") == FALSE)):
			self.currentItem = self.currentItem.itemBelow()
			i = i-1
			
		self.oldDefaultString = self.currentItem.text(0)
		self.oldDefaultString.truncate(self.oldDefaultString.find(" (default)"))
		#self.oldDefaultString.remove(0,3)
		self.currentItem.setText(0,self.oldDefaultString.latin1())
		
		self.newDefaultString = self.newDefault.text(0)
		#self.newDefaultString.prepend("<b>")
		self.newDefaultString.append(" (default)")#</b>")
		self.newDefault.setText(0,self.newDefaultString.latin1())
		
		self.defaultButton.setEnabled(FALSE)
		self.delButton.setEnabled(FALSE)		
		
		
	def onOk(self):		
		if (self.nick.text()).isEmpty() or self.nick.text().contains(" ") or self.nick.text().find('#')==0:
			self.errorBox = QMessageBox("Error !", "Invalid Nick", QMessageBox.Warning,QMessageBox.Ok,QMessageBox.NoButton,QMessageBox.NoButton,self)
			self.errorBox.show()
			self.nick.setFocus()
			self.nick.selectAll()
			return
			
		if (self.fullName.text()).isEmpty():
			self.errorBox = QMessageBox("Error !", "Please enter a full name", QMessageBox.Warning,QMessageBox.Ok,QMessageBox.NoButton,QMessageBox.NoButton,self)
			self.errorBox.show()
			self.fullName.setFocus()
			return
		
		if (self.userName.text()).isEmpty():
			self.errorBox = QMessageBox("Error !", "Please enter a user name", QMessageBox.Warning,QMessageBox.Ok,QMessageBox.NoButton,QMessageBox.NoButton,self)
			self.errorBox.show()
			self.userName.setFocus()
			return

		self.saveOptions()
		self.parent.loadOptions()

		self.close()

	def onCancel(self):
		self.close()
		
class ServerDialog(QDialog):
	def __init__(self,parent, title):
		QDialog.__init__(self, parent, "", TRUE, Qt.WStyle_Customize|Qt.WStyle_NoBorderEx|Qt.WStyle_Title)
		
		self.parent = parent
		
		self.setCaption(title)
		
		self.baseGridLayout = QGridLayout(self, 5, 3)
		self.baseGridLayout.addColSpacing(0,10)
		self.baseGridLayout.addColSpacing(2,15)
		self.baseGridLayout.addRowSpacing(0,10)
		self.baseGridLayout.addRowSpacing(2,20)
		self.baseGridLayout.addRowSpacing(4,10)
		
		self.serverGridLayout = QGridLayout(3,3)
		self.serverGridLayout.addColSpacing(1, 20)
		self.serverGridLayout.addRowSpacing(1, 10)
				
		self.serverNameLabel = QLabel("Server name :", self)
		self.serverName = QLineEdit(self)
		self.serverPortLabel = QLabel("Port :", self)
		self.serverPort = QLineEdit(self)
		self.serverPort.setMaximumWidth(40)
		self.serverPort.setMaxLength(5)
		
		
		self.serverGridLayout.addWidget(self.serverNameLabel, 0, 0)
		self.serverGridLayout.addWidget(self.serverName, 0, 2)
		self.serverGridLayout.addWidget(self.serverPortLabel, 2, 0)
		self.serverGridLayout.addWidget(self.serverPort, 2,2,Qt.AlignLeft)
		
		self.baseGridLayout.addLayout(self.serverGridLayout, 1, 1)
		
		self.serverName.setFocus()
		
		self.buttonGridLayout = QGridLayout(1,3)
		self.buttonGridLayout.addColSpacing(1,5)
		self.buttonGridLayout.setColStretch(0,1)
		self.buttonGridLayout.setColStretch(2,1)
		
		self.okButton = QPushButton("OK",self)
		self.okButton.setMaximumSize(60,25)
		self.buttonGridLayout.addWidget(self.okButton, 0,0,)#Qt.AlignRight)
		
		self.cancelButton = QPushButton("Cancel",self)
		self.cancelButton.setMaximumSize(80,25)
		self.buttonGridLayout.addWidget(self.cancelButton, 0,2)#,Qt.AlignLeft)
		
		self.baseGridLayout.addLayout(self.buttonGridLayout, 3,1)
				
		self.connect(self.okButton, SIGNAL("clicked()"), self.onOk)
		self.connect(self.cancelButton, SIGNAL("clicked()"), self.onCancel)
		
		self.show()
	
	def onOk(self):
		
		if( (self.serverName.text().isEmpty()) or (self.serverName.text().contains(" "))):
			self.errorBox = QMessageBox("Error !", "Invalid server name", QMessageBox.Warning,QMessageBox.Ok,QMessageBox.NoButton,QMessageBox.NoButton,self)
			self.errorBox.show()
			self.serverName.setFocus()
			self.serverName.selectAll()
			return
			
		try:
			self.intPort = int(self.serverPort.text().latin1())
		except:
			self.errorBox = QMessageBox("Error !", "Invalid port number", QMessageBox.Warning,QMessageBox.Ok,QMessageBox.NoButton,QMessageBox.NoButton,self)
			self.errorBox.show()
			self.serverPort.setFocus()
			self.serverPort.selectAll()
			return
			
		if(self.intPort<1 or self.intPort>65535):
			self.errorBox = QMessageBox("Error !", "Invalid port number", QMessageBox.Warning,QMessageBox.Ok,QMessageBox.NoButton,QMessageBox.NoButton,self)
			self.errorBox.show()
			self.serverPort.setFocus()
			self.serverPort.selectAll()
			return
			
		self.parent.setServerNameString(self.serverName.text())
		self.parent.setServerPortString(self.serverPort.text())
		
		self.close()		
			
		
	def onCancel(self):
		self.parent.setServerNameString("")
		self.close()