#from __future__ import unicode_literals
# -*- coding: utf-8 -*-
from __future__ import division

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from Creature import Creature
from ui.ecran_editionCreature import Ui_editionCreature
from outilsSvg import *
from VueEditionForme import VueEditionForme
from EcranEditionAttaques import EcranEditionAttaques
import regles


class EcranEditionCreature(QDialog):
    """interface de creation/edition de terrains"""
    def __init__(self, creature=None, formeCases = "H", parent=None):
        """initialisation de la fenetre"""
        super (EcranEditionCreature, self).__init__()
        self.creature = creature
        self.pixGraphique = None
        self.formeCases = formeCases
        self.createWidgets()
        
        if creature == None:
            self.accesCreation()
        else:
            self.accesEdition()
        self.majAffichage("")
        self.afficheListeAttaques()
        self.majListeAttributs()
##        self.majListeInventaire()
        
    def createWidgets(self):
        """construction de l'interface"""
        #construction de l'interface
        self.ui = Ui_editionCreature()
        self.ui.setupUi(self)
        self.connect(self.ui.enregistrerCreature, SIGNAL("clicked()"), self.enregistrer)
        self.connect(self.ui.annulerCreature, SIGNAL("clicked()"), self.annuler)
        self.connect(self.ui.supprimerCreature, SIGNAL("clicked()"), self.supprimer)
        self.connect(self.ui.idCreature, SIGNAL("textEdited(QString)"), self.majAffichage)
        self.connect(self.ui.nomCreature, SIGNAL("textEdited(QString)"), self.majAffichage)
        self.connect(self.ui.couleurCreature, SIGNAL("clicked()"), self.selectionCouleur)

        self.connect(self.ui.imgTextureCreature, SIGNAL("textEdited(QString)"), self.majApercuImage)
        self.connect(self.ui.imgLogoCreature, SIGNAL("textEdited(QString)"), self.majApercuImage)
        self.connect(self.ui.imgAfficherCreature, SIGNAL("stateChanged(int)"), self.majApercuImage)
        self.connect(self.ui.imgPivoteCreature, SIGNAL("stateChanged(int)"), self.majApercuImage)
        self.connect(self.ui.imgMasqueCreature, SIGNAL("stateChanged(int)"), self.majApercuImage)
        self.connect(self.ui.imgTailleXCreature, SIGNAL("valueChanged(int)"), self.majApercuImage)
        self.connect(self.ui.imgTailleYCreature, SIGNAL("valueChanged(int)"), self.majApercuImage)
        self.connect(self.ui.imgPosXCreature, SIGNAL("valueChanged(int)"), self.majApercuImage)
        self.connect(self.ui.imgPosYCreature, SIGNAL("valueChanged(int)"), self.majApercuImage)
        self.connect(self.ui.imgRotationCreature, SIGNAL("valueChanged(int)"), self.majApercuImage)
        self.connect(self.ui.imgReinitCreature, SIGNAL("clicked()"), self.reinitImage)

        self.connect(self.ui.nomCreature, SIGNAL("textEdited(QString)"), self.majApercuTexte)
        self.connect(self.ui.txtAfficherCreature, SIGNAL("stateChanged(int)"), self.majApercuTexte)
        self.connect(self.ui.txtTaillePoliceCreature, SIGNAL("valueChanged(int)"), self.majApercuTexte)
        self.connect(self.ui.txtGrasCreature, SIGNAL("stateChanged(int)"), self.majApercuTexte)
        self.connect(self.ui.txtPosXCreature, SIGNAL("valueChanged(int)"), self.majApercuTexte)
        self.connect(self.ui.txtPosYCreature, SIGNAL("valueChanged(int)"), self.majApercuTexte)
        self.connect(self.ui.txtRotationCreature, SIGNAL("valueChanged(int)"), self.majApercuTexte)
        self.connect(self.ui.txtReinitCreature, SIGNAL("clicked()"), self.reinitTexte)

        self.vueForme = VueEditionForme(self, self.formeCases)
        self.vueForme.creer()

        self.ui.listeAttributs.setColumnWidth(0, (0.4*self.ui.listeAttributs.width())) 
        self.ui.listeAttributs.setColumnWidth(1, (0.4*self.ui.listeAttributs.width()))
        self.connect(self.ui.listeAttributs, SIGNAL("cellChanged(int,int)"), self.listeAttributCelluleModifiee, Qt.UniqueConnection)

##        self.ui.listeInventaireCreature.setColumnWidth(0, (0.2*self.ui.listeInventaireCreature.width()))
##        self.ui.listeInventaireCreature.setColumnWidth(1, (0.8*self.ui.listeInventaireCreature.width()))
##        self.connect(self.ui.listeInventaireCreature, SIGNAL("clicked()"), self.listeInventaireCelluleModifiee)
##        self.connect(self.ui.supprimerInventaireCreature, SIGNAL("clicked()"), self.supprimerLigneListeInventaire)
##        self.connect(self.ui.ajouterInventaireCreature, SIGNAL("clicked()"), self.ajouterLigneListeInventaire)
   
        
    def accesEdition(self):
        """ouverture en mode edition"""
        self.ui.idCreature.setEnabled(True)
       
        self.ui.idCreature.setText(QString.fromUtf8(str(self.creature.id)))
        self.ui.nomCreature.setText(QString.fromUtf8(str(self.creature.nom)))
        self.ui.notesCreature.setText(QString.fromUtf8(str(self.creature.notes)))
        
        if self.creature.couleur.isValid():
            self.ui.affichageCouleurCreature.setStyleSheet("QLabel {backGround:%s}" %(self.creature.couleur.name()))
        self.ui.imgLogoCreature.setText(QString.fromUtf8(str(self.creature.logo)))
        self.ui.imgTextureCreature.setText(QString.fromUtf8(str(self.creature.img["nom"])))
        self.ui.imgTailleXCreature.setValue(self.creature.img["kx"])
        self.ui.imgTailleYCreature.setValue(self.creature.img["ky"])
        self.ui.imgPosXCreature.setValue(self.creature.img["dx"])
        self.ui.imgPosYCreature.setValue(self.creature.img["dy"])
        self.ui.imgRotationCreature.setValue(self.creature.img["rotation"])
        self.ui.imgPivoteCreature.setChecked(self.creature.img["pivote"])
        self.ui.imgMasqueCreature.setChecked(self.creature.img["masqueAuto"])

        self.ui.txtTaillePoliceCreature.setValue(self.creature.txt["taille_police"])
        self.ui.txtGrasCreature.setChecked(self.creature.txt["gras"])

        self.ui.txtPosXCreature.setValue(self.creature.txt["dx"])
        self.ui.txtPosYCreature.setValue(self.creature.txt["dy"])
        self.ui.txtRotationCreature.setValue(self.creature.txt["rotation"])
        
        self.ui.deplacementCreature.setValue(self.creature.deplacement)
        self.ui.hauteurCreature.setValue(self.creature.hauteur)
        self.ui.volCreature.setChecked(self.creature.vol)
   
        self.vueForme.majForme(self.creature.formeDef[self.formeCases])
        self.ui.supprimerCreature.setEnabled(True)
        self.ui.idCreature.setEnabled(False)
        self.majApercuImage()
        self.majApercuTexte()

    def accesCreation(self):
        """ouverture en mode creation"""
        self.creature = Creature()
        self.ui.idCreature.setEnabled(True)
        self.ui.idCreature.setText(QString.fromUtf8(str(self.nouvelIdCreature())))
        self.ui.idCreature.setEnabled(False)
        self.majApercuImage()
        self.majApercuTexte()

    def majAffichage(self, txt):
        """verifie la validite des saisies"""
        self.ui.enregistrerCreature.setEnabled(len(self.ui.idCreature.text().toUtf8()) > 0 and len(self.ui.nomCreature.text().toUtf8()) > 0)

    def afficheListeAttaques(self):
        """insere la frame d'edition des attaques"""
        tabAttaques = self.ui.ongletsCreation.widget(1)
        editionAttaques = EcranEditionAttaques(self.creature)
        editionAttaques.setParent(tabAttaques)

    def majListeAttributs(self):
        """met a jour la liste des attributs de la creature"""
        """met a jour la liste des attributs dans le panneau de combat"""
        self.disconnect(self.ui.listeAttributs, SIGNAL("cellChanged(int,int)"), self.listeAttributCelluleModifiee)
        
        #on vide la liste
        while self.ui.listeAttributs.rowCount() > 0:
            self.ui.listeAttributs.removeRow(0)
        
        #attributs issus des regles utilisees    
        ordre = regles.ordreAttributs()
        for elt in ordre:
            ligne = ordre.index(elt)
            self.ui.listeAttributs.insertRow(ligne)
            if regles.attribut(elt).combatSeulement == True: self.ui.listeAttributs.setRowHidden(ligne, True)
            item = QTableWidgetItem(QString.fromUtf8(elt))
            item.setFlags(Qt.NoItemFlags)
            self.ui.listeAttributs.setItem(ligne, 0, item)
            self.ui.listeAttributs.setItem(ligne, 1, QTableWidgetItem(QString.fromUtf8(str(self.creature.lstCaracCreature[elt]))))
            
        self.connect(self.ui.listeAttributs, SIGNAL("cellChanged(int,int)"), self.listeAttributCelluleModifiee)

    def listeAttributCelluleModifiee(self, ligne, colonne):
        """une cellule de la liste des attributs a ete modifiee"""
        if colonne != 1:
            pass
        else:
            attribut = regles.ordreAttributs()[(ligne)]
            nouvelleVal = str(self.ui.listeAttributs.item(ligne, 1).text().toUtf8())
            valVerifiee = regles.listeControle()[attribut].controler(nouvelleVal)
            if valVerifiee != None:
                self.creature.lstCaracCreature[attribut] = valVerifiee
            else:    
                self.ui.listeAttributs.setItem(ligne, 1, QTableWidgetItem(QString.fromUtf8(str(self.creature.lstCaracCreature[attribut]))))

##    def majListeInventaire(self):
##        """met a jour la liste de l'inventaire de la creature"""
##        self.disconnect(self.ui.listeInventaireCreature, SIGNAL("cellChanged(int,int)"), self.listeInventaireCelluleModifiee)
##        
##        #on vide la liste
##        while self.ui.listeInventaireCreature.rowCount() > 0:
##            self.ui.listeInventaireCreature.removeRow(0)
##        ligne = 0
##        #attributs issus des regles utilisees
##        for objet in self.creature.inventaire:
##            self.ui.listeInventaireCreature.insertRow(ligne)
##            self.ui.listeInventaireCreature.setItem(ligne, 0, QTableWidgetItem(QString.fromUtf8(self.creature.inventaire[objet])))
##            self.ui.listeInventaireCreature.setItem(ligne, 1, QTableWidgetItem(QString.fromUtf8(objet)))
##            ligne += 1
##        self.connect(self.ui.listeInventaireCreature, SIGNAL("cellChanged(int,int)"), self.listeInventaireCelluleModifiee)
##
##    def listeInventaireCelluleModifiee(self, ligne, colonne):
##        """une cellule de la liste des attributs a ete modifiee"""
##        nouvelleVal = str(self.ui.listeInventaireCreature.item(ligne, colonne).text().toUtf8())
##        val = None
##        if colonne == 0:
##            try:
##                nbre = int(nouvelleVal)
##            except:
##                nbre = -1
##            if nbre >= 0: val = str(nbre)
##        else:
##            val = str(nouvelleVal)
##            if val in self.creature.inventaire or len(val) == 0:
##                print("cet objet existe deja ou a un nom invalide")
##                val = None
##
##        if colonne == 0:    
##            if val != None:
##                self.creature.inventaire[str(self.ui.listeInventaireCreature.item(ligne, 1).text().toUtf8())] = val
##            else:
##                self.ui.listeInventaireCreature.setItem(ligne, 0, QTableWidgetItem(QString.fromUtf8(\
##                                                        str(self.creature.inventaire[str(self.ui.listeInventaireCreature.item(ligne, 1).text().toUtf8())]))))
##        else:
##            txt = str(self.ui.listeInventaireCreature.item(ligne, 1).text().toUtf8())
##            if txt in self.creature.inventaire:
##                del self.creature.inventaire[txt]
##            if val != None:
##                self.creature.inventaire[val] = txt
##            else:    
##                self.ui.listeInventaireCreature.removeRow(ligne)
##
##    def ajouterLigneListeInventaire(self, objet=""):
##        num = -1
##        for i in range(0, self.ui.listeInventaireCreature.rowCount()):   #si un objet de la liste a deja un nom vide, on ne cree pas de nouvelle ligne
##            if len(str(self.ui.listeInventaireCreature.item(i, 0).text().toUtf8())) == 0:
##                num = i
##                break 
##        if num < 0:           
##            self.disconnect(self.ui.listeInventaireCreature, SIGNAL("cellChanged(int,int)"), self.listeInventaireCelluleModifiee)
##            ligne = self.ui.listeInventaireCreature.rowCount()
##            self.ui.listeInventaireCreature.insertRow(ligne)
##            self.ui.listeInventaireCreature.setItem(ligne, 0, QTableWidgetItem(QString.fromUtf8("0")))
##            self.ui.listeInventaireCreature.setItem(ligne, 1, QTableWidgetItem(QString.fromUtf8(objet)))
##            self.connect(self.ui.listeInventaireCreature, SIGNAL("cellChanged(int,int)"), self.listeInventaireCelluleModifiee)
##        else:
##            self.ui.listeInventaireCreature.setCurrentRow(num)
##            
##    def supprimerLigneListeInventaire(self):
##        self.disconnect(self.ui.listeInventaireCreature, SIGNAL("cellChanged(int,int)"), self.listeInventaireCelluleModifiee)
##        ligne = self.ui.listeInventaireCreature.currentRow()
##        del self.creature.inventaire[str(self.ui.listeInventaireCreature.item(ligne, 1).text().toUtf8())]
##        self.ui.listeInventaireCreature.removeRow(ligne)
##        self.connect(self.ui.listeInventaireCreature, SIGNAL("cellChanged(int,int)"), self.listeInventaireCelluleModifiee)        

    def majApercuImage(self):
        """met a jour l'image sur l'apercu du pion"""
        if self.ui.imgAfficherCreature.isChecked():
            if len(str(self.ui.imgTextureCreature.text().toUtf8())) > 0:
                img = str(self.ui.imgTextureCreature.text().toUtf8())
                self.vueForme.majImage(img, self.ui.imgTailleXCreature.value() \
                                          , self.ui.imgTailleYCreature.value() \
                                          , self.ui.imgPosXCreature.value() \
                                          , self.ui.imgPosYCreature.value() \
                                          , self.ui.imgRotationCreature.value() \
                                          , self.ui.imgPivoteCreature.isChecked() \
                                          , self.ui.imgMasqueCreature.isChecked() )
            else:
                img = str(self.ui.imgLogoCreature.text().toUtf8())
                self.vueForme.majImage(img)
        else:
            img = ""
            self.vueForme.majImage(img)

    def majApercuTexte(self):
        """met a jour l'etiquette sur l'apercu du pion"""
        if self.ui.txtAfficherCreature.isChecked():
            txt = str(self.ui.nomCreature.text().toUtf8())
        else:
            txt = "Pion"   
        self.vueForme.majTexte(txt, self.ui.txtTaillePoliceCreature.value() \
                                  , self.ui.txtGrasCreature.isChecked() \
                                  , self.ui.txtPosXCreature.value() \
                                  , self.ui.txtPosYCreature.value() \
                                  , self.ui.txtRotationCreature.value())

    def reinitImage(self):
        self.ui.imgTailleXCreature.setValue(10)
        self.ui.imgTailleYCreature.setValue(10)
        self.ui.imgPosXCreature.setValue(0)
        self.ui.imgPosYCreature.setValue(0)
        self.ui.imgRotationCreature.setValue(0)
        self.ui.imgPivoteCreature.setChecked(False)
        self.ui.imgMasqueCreature.setChecked(False)
        self.majApercuImage()

    def reinitTexte(self):
        self.ui.txtTaillePoliceCreature.setValue(21)
        self.ui.txtGrasCreature.setCheckState(0)
        self.ui.txtPosXCreature.setValue(0)
        self.ui.txtPosYCreature.setValue(0)
        self.ui.txtRotationCreature.setValue(0)
        self.majApercuTexte()        

    def nouvelIdCreature(self):
        """renvoie un identifiant pour un nouveau terrain"""
        dicoSvg = afficheSvg("lib\\biblio\\creature")
        nouvelId = 1
        while str(nouvelId) in dicoSvg.keys():
            nouvelId += 1
        return str(nouvelId)

    def selectionCouleur(self):
        """selectionne la couleur dans la boite de dialogue dediee"""
        couleur = QColorDialog(self).getColor(QColor("white"), self)
        if couleur.isValid():
            nomCouleur = couleur.name()
            self.ui.affichageCouleurCreature.setStyleSheet("QLabel {backGround:%s}" %(nomCouleur))
            self.creature.couleur = couleur    
            
    def enregistrer(self):
        """enregistre le terrain cree/edite"""
        self.creature.id = str(self.ui.idCreature.text().toUtf8())
        self.creature.nom = str(self.ui.nomCreature.text().toUtf8())
        self.creature.logo = str(self.ui.imgLogoCreature.text().toUtf8())
        if len(str(self.ui.imgTextureCreature.text().toUtf8())) > 0:
            self.creature.img["nom"] = str(self.ui.imgTextureCreature.text().toUtf8())
            self.creature.img["kx"] = self.ui.imgTailleXCreature.value()
            self.creature.img["ky"] = self.ui.imgTailleYCreature.value()
            self.creature.img["dx"] = self.ui.imgPosXCreature.value()
            self.creature.img["dy"] = self.ui.imgPosYCreature.value()
            self.creature.img["rotation"] = self.ui.imgRotationCreature.value()
            self.creature.img["pivote"] = self.ui.imgPivoteCreature.isChecked()
            self.creature.img["masqueAuto"] = self.ui.imgMasqueCreature.isChecked()
        else:
            self.creature.img["nom"] = str(self.ui.imgLogoCreature.text().toUtf8())
            self.creature.img["kx"] = 10
            self.creature.img["ky"] = 10
            self.creature.img["dx"] = 0
            self.creature.img["dy"] = 0
            self.creature.img["rotation"] = 0
            self.creature.img["pivote"] = False
            self.creature.img["masqueAuto"] = False

        self.creature.txt["taille_police"] = self.ui.txtTaillePoliceCreature.value()
        self.creature.txt["gras"] = bool(self.ui.txtGrasCreature.checkState())
        self.creature.txt["dx"] = self.ui.txtPosXCreature.value()
        self.creature.txt["dy"] = self.ui.txtPosYCreature.value()
        self.creature.txt["rotation"] = self.ui.txtRotationCreature.value()

        self.creature.deplacement = int(self.ui.deplacementCreature.value())
        self.creature.hauteur = int(self.ui.hauteurCreature.value())
        self.creature.vol = self.ui.volCreature.isChecked()

        self.creature.formeDef[self.formeCases] = self.vueForme.formeDef()

        self.creature.notes = str(self.ui.notesCreature.toPlainText())
        #attributs, attaques et inventaire enregistres lors de la modif des listes
        
        enregistrer(self.creature.id, self.creature, "lib\\biblio\\creature")
        self.creature = None
        self.emit(SIGNAL("majListCreatures()"))
        self.close()

    def supprimer(self):
        """supprimer l'enregistrement de ce terrain"""
        supprSvg("lib\\biblio\\creature", self.creature.id)
        self.emit(SIGNAL("majListCreatures()"))
        self.close()

    def annuler(self):
        """annule la creation/edition"""
        self.creature = None
        self.close()
