#!/usr/bin/python
# -*- coding: utf-8 -*-

from PyQt4 import QtCore, QtGui
import os, codecs
import guinewconf, guidelete


def updateUi(self, MyHighlighter):
    """Updates self.ui_prefs"""
    #Change font of textEdits
    self.ui_prefs.textEdit.setFont(self.myfont)
    self.ui_prefs.textEdit_generate.setFont(self.myfont)
    #Set up highlighting
    self.highlighter1 = MyHighlighter(self.ui_prefs.textEdit)
    self.highlighter2 = MyHighlighter(self.ui_prefs.textEdit_generate)
    #Fill everything
    self.ui_prefs.lineEdit_ex_folder.setText(self.settings["tex_path"])
    self.ui_prefs.lineEdit_save_folder.setText(self.settings["save_location"])
    self.ui_prefs.textEdit
    self.ui_prefs.textEdit.setText(self.header)
    #About the generate exam button :
    self.ui_prefs.lineEdit_dvi_viewer.setText(self.settings["file_viewer"])
    for k in range(self.ui_prefs.comboBox.count()):
        if self.ui_prefs.comboBox.itemText(k) == self.settings["type_of_file"]:
            self.ui_prefs.comboBox.setCurrentIndex(k)
            break
    #Add tags to the listWidget :
    for i in range(len(self.tags[0])):
        t1 = self.tags[0][i]
        t2 = self.tags[1][i]
        item = QtGui.QListWidgetItem(self.ui_prefs.listWidget)
        item.setText(t1+u" ... "+t2)
        item.t1 = t1
        item.t2 = t2
    #Add compile commands to the listWidget_comp
    for i in range(len(self.compile_seq)):
        item = QtGui.QListWidgetItem(self.ui_prefs.listWidget_comp)
        item.setText(self.compile_seq[i].replace("/tmp/partielator/file","!file"))
        item.c = self.compile_seq[i].replace("/tmp/partielator/file","!file")
    #Add elements to the generate comboBox and fills the textEdit_generate
    keys = self.generate.keys()
    keys.sort(key=str.lower)
    for key in keys:
        if key != "Add ...":
            self.ui_prefs.comboBox_gen.addItem(key) #add key to the combobox
        self.generate[key] = [self.generate[key]] #to keep track of changes
    self.ui_prefs.comboBox_gen.addItem("Add ...")
    if keys[0] == "Add ...":
        self.last_generate = keys[1]
    else:
        self.last_generate = keys[0]
    if self.last_generate == "Same header":
        self.ui_prefs.pushButton_delete.setEnabled(False)
    self.ui_prefs.textEdit_generate.setText(self.generate[self.last_generate][0])
    self.combo(self.last_generate)
    #Is preview package used ?
    if self.settings["use_preview"] == "True":
        self.ui_prefs.radioButton_yes.setChecked(True)
        self.ui_prefs.radioButton_no.setChecked(False)
    else:
        self.ui_prefs.radioButton_no.setChecked(True)
        self.ui_prefs.radioButton_yes.setChecked(False)
    #Signals and slots
    QtCore.QObject.connect(self.ui_prefs.pushButton_parcourir_tex_path,QtCore.SIGNAL("clicked()"),self.parcourir_tex_path)
    QtCore.QObject.connect(self.ui_prefs.pushButton_parcourir_sav,QtCore.SIGNAL("clicked()"),self.parcourir_sav)
    QtCore.QObject.connect(self.ui_prefs.pushButton_remove,QtCore.SIGNAL("clicked()"),self.removetags)
    QtCore.QObject.connect(self.ui_prefs.pushButton_add,QtCore.SIGNAL("clicked()"),self.addtags)
    QtCore.QObject.connect(self.ui_prefs.pushButton_addc,QtCore.SIGNAL("clicked()"),self.addtocompileseq)
    QtCore.QObject.connect(self.ui_prefs.pushButton_removec,QtCore.SIGNAL("clicked()"),self.removefromcompileseq)
    QtCore.QObject.connect(self.ui_prefs.pushButton_up,QtCore.SIGNAL("clicked()"),self.goup2)
    QtCore.QObject.connect(self.ui_prefs.pushButton_down,QtCore.SIGNAL("clicked()"),self.godown2)
    QtCore.QObject.connect(self.ui_prefs.comboBox_gen,QtCore.SIGNAL("currentIndexChanged(QString)"),self.combo)
    QtCore.QObject.connect(self.ui_prefs.textEdit,QtCore.SIGNAL("textChanged()"),self.update_generate_header)
    QtCore.QObject.connect(self.ui_prefs.pushButton_delete,QtCore.SIGNAL("clicked()"),self.prefs_delete)


def close_prefs(self, res):
    """When the prefs window is closed"""
    if res:
        #If user cliked ok, change settings and write it in the config file
        #Basic settings
        self.settings["tex_path"] = unicode(self.ui_prefs.lineEdit_ex_folder.text())
        self.settings["save_location"] = unicode(self.ui_prefs.lineEdit_save_folder.text())
        self.settings["file_viewer"] = unicode(self.ui_prefs.lineEdit_dvi_viewer.text())
        self.settings["type_of_file"] = unicode(self.ui_prefs.comboBox.currentText())
        self.header = unicode(self.ui_prefs.textEdit.toPlainText())
        if self.ui_prefs.radioButton_yes.isChecked():
            self.settings["use_preview"] = "True"
        else:
            self.settings["use_preview"] = "False"
        home_dir = os.path.expanduser("~")
        f = codecs.open(os.path.join(home_dir, ".partielator", "basics"), 'w', "utf-8")
        for key, value in self.settings.iteritems():
            f.write(key + "=" + str(value) + "\n")
        f.close()
        #Header
        g = codecs.open(os.path.join(home_dir, ".partielator", "header"), 'w', "utf-8")
        g.write(unicode(self.ui_prefs.textEdit.toPlainText()))
        g.close()
        self.header = unicode(self.ui_prefs.textEdit.toPlainText())
        self.lineEdit.setText(self.settings["tex_path"])
        #Tags
        h = codecs.open(os.path.join(home_dir, ".partielator", "tags"), 'w', "utf-8")
        self.tags = [[], []]
        for i in range(self.ui_prefs.listWidget.count()):
            t1 = self.ui_prefs.listWidget.item(i).t1
            t2 = self.ui_prefs.listWidget.item(i).t2
            self.tags[0].append(t1)
            self.tags[1].append(t2)
            h.write(t1 + "!!!" + t2 + "\n")
        h.close()
        #Compile sequence
        self.compile_seq = []
        k = codecs.open(os.path.join(home_dir, ".partielator", "compile_seq"), 'w', "utf-8")
        for i in range(self.ui_prefs.listWidget_comp.count()):
            c = self.ui_prefs.listWidget_comp.item(i).text()
            k.write(c + "\n")
            self.compile_seq.append(c)
        k.close()
        #Generate
        self.generate[self.last_generate].append(unicode(self.ui_prefs.textEdit_generate.toPlainText()))
        for key in self.generate.keys():
            a = self.generate[key][-1] #dict was messed up so as to keep track of changes
            self.generate[key] = a
            if key == "Add ..." or key == "Same header":
                continue
            f = codecs.open(os.path.join(home_dir, ".partielator", "generate",key), 'w', 'utf-8')
            f.write(a)
            f.close()
    else:
        #Un-mess up the dictionnary
        for key in self.generate.keys():
            self.generate[key] = self.generate[key][0]



def combo(self, text):
    """Dealing with generate configs"""
    #Before doing anything, see if the last config used one has changed
    a = str(text)
    if unicode(self.ui_prefs.textEdit_generate.toPlainText()) != self.generate[self.last_generate][-1]\
    and text != "Same header" and text != "Add ...":
        self.generate[self.last_generate].append(unicode(self.ui_prefs.textEdit_generate.toPlainText()))
    
    if text == "Add ...":
        Dialog_newconf = QtGui.QDialog()
        self.ui_newconf = guinewconf.Ui_Dialog()
        self.ui_newconf.setupUi(Dialog_newconf)
        res = Dialog_newconf.exec_()
        newkey = str(self.ui_newconf.lineEdit.text())
        if res and not newkey in self.generate.keys():
            if not newkey:
                self.combo(text)
                return
            self.generate[newkey] = ["\n\n\\begin{document}\n\n\n\n\n%Your exercises will be written at the end of this file"]
            length = self.ui_prefs.comboBox_gen.count()
            for k in range(length):#insert alphabetically newkey
                if newkey.lower() < str(self.ui_prefs.comboBox_gen.itemText(k)).lower():
                    self.ui_prefs.comboBox_gen.setCurrentIndex(0)#if not present insertItem sends a bad signal
                    self.ui_prefs.comboBox_gen.insertItem(k,newkey)
                    self.ui_prefs.comboBox_gen.setCurrentIndex(k)
                    break
            if k == length-1:
                self.ui_prefs.comboBox_gen.setCurrentIndex(0)#if not present insertItem sends a bad signal
                self.ui_prefs.comboBox_gen.insertItem(k,newkey)
                self.ui_prefs.comboBox_gen.setCurrentIndex(k)
            self.last_generate = newkey
            self.ui_prefs.pushButton_delete.setEnabled(True)
        else:
            self.ui_prefs.comboBox_gen.setCurrentIndex(0)
            if self.last_generate == "Same header":
                self.ui_prefs.pushButton_delete.setEnabled(False)
            else:
                self.ui_prefs.pushButton_delete.setEnabled(True)

    elif text == "Same header":
        self.ui_prefs.textEdit_generate.setReadOnly(True)
        self.ui_prefs.textEdit_generate.setText(self.generate[a][-1]+"\n\\begin{document}")
        self.last_generate = a
        self.ui_prefs.pushButton_delete.setEnabled(False)
    else:
        self.ui_prefs.textEdit_generate.setReadOnly(False)
        self.ui_prefs.textEdit_generate.setText(self.generate[a][-1])
        self.last_generate = a
        self.ui_prefs.pushButton_delete.setEnabled(True)


def update_generate_header(self):
    self.generate["Same header"][-1] = unicode(self.ui_prefs.textEdit.toPlainText())
    if self.last_generate == "Same header":
        self.ui_prefs.textEdit_generate.setText(self.generate["Same header"][-1])


def parcourir_tex_path(self):
    dirName = QtGui.QFileDialog.getExistingDirectory(self.Dialog_prefs,"Pick a folder",
                self.settings["tex_path"])
    if dirName:
        self.ui_prefs.lineEdit_ex_folder.setText(dirName)

def parcourir_sav(self):
    dirName = QtGui.QFileDialog.getExistingDirectory(self.Dialog_prefs,"Pick a folder",
                    self.settings["save_location"])
    if dirName:
        self.ui_prefs.lineEdit_save_folder.setText(dirName)

def removetags(self):
    self.ui_prefs.listWidget.takeItem(self.ui_prefs.listWidget.currentRow())

def addtags(self):
    if unicode(self.ui_prefs.lineEdit_tag1.text()) and unicode(self.ui_prefs.lineEdit_tag2.text()):
        item = QtGui.QListWidgetItem(self.ui_prefs.listWidget)
        item.t1 = unicode(self.ui_prefs.lineEdit_tag1.text())
        item.t2 = unicode(self.ui_prefs.lineEdit_tag2.text())
        item.setText(item.t1 + u" ... " + item.t2)

def addtocompileseq(self):
    if unicode(self.ui_prefs.lineEdit_command.text()):
        item = QtGui.QListWidgetItem(self.ui_prefs.listWidget_comp)
        item.setText(unicode(self.ui_prefs.lineEdit_command.text()))

def prefs_delete(self):
    Dialog_delete = QtGui.QDialog()
    self.ui_delete = guidelete.Ui_Dialog()
    self.ui_delete.setupUi(Dialog_delete)
    i = self.ui_prefs.comboBox_gen.currentIndex()
    text = str(self.ui_prefs.comboBox_gen.currentText())
    self.ui_delete.label.setText("You are about to delete the config : " + text)
    res = Dialog_delete.exec_()
    if res:
        self.ui_prefs.comboBox_gen.removeItem(i)
        del self.generate[text]
        home_dir = os.path.expanduser("~")
        os.remove(os.path.join(home_dir,".partielator","generate",text))
