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

############################################################################################################################################
#                                               IrcClientChannelFolderDialog                           
############################################################################################################################################

TRUE = 1
FALSE = 0

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

		self.parent = parent

		self.channelString = ""
		self.channelDescriptionString = ""
		#self.prevServer = ""
		
		self.serverDic = {}
		
		self.connection = con
		self.setCaption("Qt ProgXRC - Channels folder")
		
		baseGridLayout = QGridLayout(self,5,3)

		baseGridLayout.addColSpacing(0,10)
		baseGridLayout.addColSpacing(2,10)
		baseGridLayout.addRowSpacing(0,10)
		baseGridLayout.addRowSpacing(2,30)
		baseGridLayout.addRowSpacing(4,10)
		
		self.upGridLayout = QGridLayout(3,3)
		self.upGridLayout.addColSpacing(1,20)
		self.upGridLayout.addRowSpacing(1,5)
		self.upGridLayout.setColStretch(0,1)
		self.upGridLayout.setColStretch(2,1)
		
		self.connectButton = QPushButton("Connect",self)
		self.connectButton.setMaximumSize(60,25)
		self.upGridLayout.addWidget(self.connectButton, 2,2,Qt.AlignLeft)
		
		self.selectLabel = QLabel("Select a server :",self)
		self.serverListBox = QListBox(self)
		self.serverListBox.resize(200,60)
		self.serverListBox.setMaximumHeight(60)
		
		self.loadServers()
		self.fillServerDic()
		
		self.upGridLayout.addWidget(self.selectLabel, 0,0, Qt.AlignLeft)
		self.upGridLayout.addWidget(self.serverListBox, 2,0,Qt.AlignLeft)
		
		baseGridLayout.addLayout(self.upGridLayout, 1,1)
		
		self.downGridLayout = QGridLayout(1,3)
		self.downGridLayout.addColSpacing(1,10)
		
		self.downLeftGridLayout = QGridLayout(5,1)
		self.downLeftGridLayout.addRowSpacing(1,5)
		self.downLeftGridLayout.addRowSpacing(3,10)
				
		self.channelLabel = QLabel("Enter name of channel :", self)
		self.channelLabel.setMaximumSize(150,20)
		
		self.channel = QLineEdit(self)
		self.channel.setMaximumSize(300,20)
		self.channel.setFocus()
		
		self.channelListView = QListView(self)
		self.channelListView.setMaximumSize(300,223)
		self.channelListView.setHScrollBarMode(QScrollView.AlwaysOn)
		self.channelListView.setVScrollBarMode(QScrollView.AlwaysOn)
		self.channelListView.addColumn("Channel")
		self.channelListView.addColumn("Description")
		self.channelListView.setAllColumnsShowFocus(TRUE)
		self.channelListView.setColumnWidth(1,280-self.channelListView.columnWidth(0))
		
		self.downLeftGridLayout.addWidget(self.channelLabel, 0,0, Qt.AlignLeft)
		self.downLeftGridLayout.addWidget(self.channel, 2,0)
		self.downLeftGridLayout.addWidget(self.channelListView, 4,0)
		
		self.downGridLayout.addLayout(self.downLeftGridLayout, 0,0)
		
						
		self.downRightGridLayout = QGridLayout(11,1)
		self.downRightGridLayout.addRowSpacing(1,5)
		self.downRightGridLayout.addRowSpacing(5,5)
		self.downRightGridLayout.addRowSpacing(7,5)
		self.downRightGridLayout.setRowStretch(3,1)
		self.downRightGridLayout.setRowStretch(9,1)
		
		self.joinButton = QPushButton("Join",self)
		self.joinButton.setMaximumSize(60,25)
		self.joinButton.setEnabled(FALSE)
		
		self.downRightGridLayout.addWidget(self.joinButton, 0,0)
		
		self.namesButton = QPushButton("Names",self)
		self.namesButton.setMaximumSize(60,25)
		self.namesButton.setEnabled(FALSE)
		
		self.downRightGridLayout.addWidget(self.namesButton, 2,0)
		
		self.addButton = QPushButton("Add",self)
		self.addButton.setMaximumSize(60,25)
		self.addButton.setEnabled(FALSE)
		
		self.downRightGridLayout.addWidget(self.addButton, 4,0)
		
		self.editButton = QPushButton("Edit",self)
		self.editButton.setMaximumSize(60,25)
		self.editButton.setEnabled(FALSE)
		
		self.downRightGridLayout.addWidget(self.editButton, 6,0)
		
		self.deleteButton = QPushButton("Delete",self)
		self.deleteButton.setMaximumSize(60,25)
		self.deleteButton.setEnabled(FALSE)
		
		self.downRightGridLayout.addWidget(self.deleteButton, 8,0)
		
		self.okButton = QPushButton("OK",self)
		self.okButton.setMaximumSize(60,25)
		
		self.downRightGridLayout.addWidget(self.okButton, 10,0)
		
		self.downGridLayout.addLayout(self.downRightGridLayout, 0,2)
		
		baseGridLayout.addLayout(self.downGridLayout, 3,1)
		
		self.connect(self.serverListBox, SIGNAL("highlighted(const QString&)"), self.onServerListBoxSimpleClick)
		self.connect(self.channelListView, SIGNAL("selectionChanged(QListViewItem*)"), self.onChannelListViewClicked)
		self.connect(self.channel, SIGNAL("textChanged(const QString&)"), self.onChannelTextChanged) 
		self.connect(self.joinButton, SIGNAL("clicked()"), self.onJoin)
		self.connect(self.namesButton, SIGNAL("clicked()"), self.onNames)
		self.connect(self.addButton, SIGNAL("clicked()"), self.onAdd)
		self.connect(self.editButton, SIGNAL("clicked()"), self.onEdit)
		self.connect(self.deleteButton, SIGNAL("clicked()"), self.onDelete)
		self.connect(self.okButton, SIGNAL("clicked()"), self.onOk)
		self.connect(self.connectButton, SIGNAL("clicked()"), self.onConnect)
				
		self.show()
		
	def onServerListBoxSimpleClick(self, serverName):
		self.channelListView.clear()
		self.addButton.setEnabled(TRUE)
		
		name = serverName.latin1().decode("ISO-8859-1")
		for channelNameIndex in range(0,len(self.serverDic[name]), 2):
			channelName = self.serverDic[name][channelNameIndex]
			channelDescription = self.serverDic[name][channelNameIndex+1]
			QListViewItem(self.channelListView, channelName, channelDescription)
		
	def onChannelListViewClicked(self, listLine):
		self.channel.setText(listLine.text(0))
		self.editButton.setEnabled(TRUE)
		self.deleteButton.setEnabled(TRUE)
		
	def onChannelTextChanged(self, newChannelText):
		if newChannelText.latin1() == "":
			self.joinButton.setEnabled(FALSE)
			self.namesButton.setEnabled(FALSE)
		else:
			self.joinButton.setEnabled(TRUE)
			self.namesButton.setEnabled(TRUE)

	def onConnect(self):
		name = self.serverListBox.currentText()
		if name == None:
			return
		server = name.latin1().decode("ISO-8859-1")

		self.parent.connectTo(server)

		self.saveChannelList()
		self.close()

	def onJoin(self):
		self.saveChannelList()
		self.connection.join([self.channel.text().latin1()])
		self.close()
		
	def onNames(self):
		self.connection.names([self.channel.text().latin1()])
			
	def onAdd(self):
		self.addDialog = ChannelDialog(self,"Qt PROGXRC - Add Channel")
		
		if self.channelString != "":
			if self.channelString[0] != "#":
				self.channelString = "#" + self.channelString
							
			self.channelToAddItem = QListViewItem(self.channelListView, self.channelString, self.channelDescriptionString)
			name = self.serverListBox.currentText().latin1().decode("ISO-8859-1")
			self.serverDic[name].append(self.channelString)
			self.serverDic[name].append(self.channelDescriptionString)
		
	def onEdit(self):
		self.editDialog = ChannelDialog(self,"Qt PROGXRC - Edit Channel", \
						(self.channelListView.currentItem()).text(0),\
									(self.channelListView.currentItem()).text(1))
		
		if self.channelString.latin1() != "":
			if self.channelString.latin1()[0] != "#":
				self.channelString = "#" + self.channelString.latin1()
				
			self.channelListView.currentItem().setText(0, self.channelString)
			self.channelListView.currentItem().setText(1, self.channelDescriptionString)
			self.channel.setText(self.channelString)
			 
			name = self.serverListBox.currentText().latin1().decode("ISO-8859-1")
			self.serverDic[name] = []
			
			i = self.channelListView.childCount()
			tempListViewItem = self.channelListView.firstChild()
			
			while(i>0):
				self.serverDic[name].append(tempListViewItem.text(0).latin1())
				self.serverDic[name].append(tempListViewItem.text(1).latin1())
				tempListViewItem = tempListViewItem.itemBelow()
				i = i-1
			
	def onDelete(self):
		self.channelListView.takeItem(self.channelListView.selectedItem())
		self.channel.setText("")
		
		if self.channelListView.selectedItem() == None:
			self.editButton.setEnabled(FALSE)
			self.deleteButton.setEnabled(FALSE)

		name = self.serverListBox.currentText().latin1().decode("ISO-8859-1")
		self.serverDic[name] = []
			
		i = self.channelListView.childCount()
		tempListViewItem = self.channelListView.firstChild()
		
		while(i>0):
			self.serverDic[name].append(tempListViewItem.text(0).latin1())
			self.serverDic[name].append(tempListViewItem.text(1).latin1())
			tempListViewItem = tempListViewItem.itemBelow()
			i = i-1
			
	def onOk(self):
		self.saveChannelList()
		self.close()
		
	def setChannelString(self, stringToSet):
		self.channelString = stringToSet
		
	def setChannelDescriptionString(self, stringToSet):
		self.channelDescriptionString = stringToSet
		
	def loadServers(self):
		try:
			xmldoc = parse("options.xml")
			for xmlRootChildren in xmldoc.documentElement.childNodes:
				if( xmlRootChildren.nodeName == "serverlist"):
					for xmlServer in xmlRootChildren.childNodes:
						for xmlServerParam in xmlServer.childNodes:
							if(xmlServerParam.nodeName == "server-name"):
								serverName = string.strip(xmlServerParam.firstChild.nodeValue)
								self.serverListBox.insertItem(serverName)
								self.serverDic[serverName] = []
		except:
			return
			
	def fillServerDic(self):
		try:
			xmldoc = parse("channel-folder.xml")
			for server in xmldoc.documentElement.getElementsByTagName("server"):
				name = server.attributes["name"].value
				for channel in server.getElementsByTagName("channel"):
					self.serverDic[name].append(channel.attributes["name"].value)
					try:
						self.serverDic[name].append(string.strip(channel.firstChild.nodeValue))
					except:
						self.serverDic[name].append("")
		except:
			return
		
	def saveChannelList(self):
		xmldoc = Document()
		xmlRoot = xmldoc.createElement("channel-folder")
		
		for serverName in self.serverDic.keys():
			serverTag = xmldoc.createElement("server")
			serverTag.setAttribute("name", serverName)
						
			for channelNameIndex in range(0,len(self.serverDic[serverName]), 2):
				channelName = self.serverDic[serverName][channelNameIndex]
				channelName.encode("ISO-8859-1")
				channelTag = xmldoc.createElement("channel")
				channelTag.setAttribute("name", channelName)
				channelTag.appendChild(xmldoc.createTextNode( (self.serverDic[serverName][channelNameIndex+1]).encode("ISO-8859-1") ))
				serverTag.appendChild(channelTag)
				
			xmlRoot.appendChild(serverTag)
			
		xmldoc.appendChild(xmlRoot)
		
		xmlFile = open("channel-folder.xml", "w")
		xmldoc.encoding = "ISO-8859-1"
		xmldoc.actualEncoding = "ISO-8859-1"
		xmlFile.write(xmldoc.toprettyxml().encode("ISO-8859-1").replace("""<?xml version="1.0" ?>""", """<?xml version="1.0" encoding="ISO-8859-1"?>""")) 
		xmlFile.close()
		xmldoc.unlink()
		
class ChannelDialog(QDialog):
	def __init__(self,parent, title, channel="", description=""):
		QDialog.__init__(self, parent, "", TRUE, Qt.WStyle_Customize|Qt.WStyle_NoBorderEx|Qt.WStyle_Title)
		
		self.parent = parent
		
		self.setCaption(title)
		self.resize(250,120)
		
		self.channelLabel = QLabel("Channel name :", self)
		self.channelLabel.resize(150,20)
		self.channelLabel.move(10,10)
		
		self.channel = QLineEdit(self)
		self.channel.move(90,10)
		self.channel.resize(150,20)
		self.channel.setText(channel)
		self.channel.setFocus()
			
		self.channelDescriptionLabel = QLabel("Description :", self)
		self.channelDescriptionLabel.resize(100,20)
		self.channelDescriptionLabel.move(10,50)
		
		self.channelDescription = QLineEdit(self)
		self.channelDescription.move(90,50)
		self.channelDescription.resize(150,20)
		self.channelDescription.setText(description)
		
		
		self.okButton = QPushButton("OK",self)
		self.okButton.resize(60,25)
		self.okButton.move(45,85)
		
		self.cancelButton = QPushButton("Cancel",self)
		self.cancelButton.resize(80,25)
		self.cancelButton.move(125,85)
		
		
		self.connect(self.okButton, SIGNAL("clicked()"), self.onOk)
		self.connect(self.cancelButton, SIGNAL("clicked()"), self.onCancel)
		
		self.show()
		
	def onOk(self):
		
		if (self.channel.text()).isEmpty():
			self.errorBox = QMessageBox("Error !", "Please enter a channel name", QMessageBox.Warning,QMessageBox.Ok,QMessageBox.NoButton,QMessageBox.NoButton,self)
			
			self.errorBox.show()
			self.channel.setFocus()
			return
			
		self.parent.setChannelString(self.channel.text().latin1())
		self.parent.setChannelDescriptionString(self.channelDescription.text().latin1())
		
		self.close()
		
	def onCancel(self):
		
		self.parent.setChannelString("")
		self.close()
