#from __future__ import unicode_literals
# -*- coding: utf-8 -*-
"""les modes d'interaction permettent l'interaction
entre l'interface (l'utilisateur) et le plateau de combat.
Un seul mode ne peut etre actif a la fois
Cette classe doit permettre de recevoir les commandes de l'utilisateur
de maniere a produire un resultat unique (cases peintes, pion deplace...)"""
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from EntreeSortie import EntreeSortie
import Actions
import regles

class ModeBase(object):
    """mode de base: tous les modes heritent de cette classe"""
    def __init__(self, plateau):
        self.plateau = plateau
        #le mode est il active
        self._actif = False
        #le dragmode est il active sur la QGraphicsView
        self._activerDragMode = 0
        #curseur de la QGraphicsView
        self._sourceCurseur = ""
        #met le focus sur la QGraphicsView a l'activation
        self._focus = False 

    def nom(self):
        return self.__class__.__name__

    def activer(self, param = None):
        """active le mode"""
        self.activerCurseur()
        if self._focus:
            self.plateau.fenetre.ui.cbt_vue.setFocus()
        self._actif = True    

    def desactiver(self):
        """desactive le mode"""
        self.desactiverCurseur()
        self.plateau.fenetre.ui.cbt_vue.setDragMode(1)
        self._actif = False

    def reinit(self):
        """remet les variables a 0 et reactive le mode"""
        pass

    def activerCurseur(self):
        self.plateau.fenetre.ui.cbt_vue.setDragMode(self._activerDragMode)
        curseurPix = QPixmap(self._sourceCurseur)
        if not curseurPix.isNull():
            curseur = QCursor(curseurPix, 0, curseurPix.height())
            self.plateau.fenetre.ui.cbt_vue.setCursor(curseur)   

    def desactiverCurseur(self):
        self.plateau.fenetre.ui.cbt_vue.setCursor(QCursor(Qt.ArrowCursor))

    ### gestion des evenements souris
    # clic gauche
    def clic_combattant(self, num):
        pass

    def clic_decor(self, num):
        pass

    def clic_case(self, coord):
        pass

    #double clic gauche
    def doubleClic_combattant(self, num):
        pass

    def doubleClic_decor(self, num):
        pass

    def doubleClic_case(self, coord):
        pass

    #survol de la souris (entree)   
    def survol_combattant(self, num):
        pass

    def survol_decor(self, num):
        pass

    def survol_case(self, coord):
        pass

    #survol de la souris (sortie)  
    def finSurvol_combattant(self, num):
        pass

    def finSurvol_decor(self, num):
        pass

    def finSurvol_case(self, coord):
        pass

    #survol de la souris avec clic gauche enfonce (entree)   
    def survolClic_combattant(self, event):
        pass

    def survolClic_decor(self, event):
        pass

    def survolClic_case(self, coord):
        pass

    #autre
    def clicGauche(self, event):
        pass

    def finClicGauche(self, event):
        pass
    
    def mouvementSouris(self, event):
        pass
    
    def toucheClavier(self, event):
        pass

    def clicDroit(self, event):
        pass


class ModeBaseCp(ModeBase):
    """mode servant de base a tous les modes lies a la creation de plateau"""
    def __init__(self, plateau):
        super(ModeBaseCp, self).__init__(plateau)
        self.type = "cp"

    def clicDroit(self, event):
        self.plateau.activerMode(StandardCp)


class ModeBasePi(ModeBase):
    """mode servant de base a tous les modes lies aux actions des combattants"""
    def __init__(self, plateau):
        super(ModeBasePi, self).__init__(plateau)
        self.type = "pi"

    def clicDroit(self, event):
        self.plateau.activerMode(StandardPi)

### --------------------------------------- ####


class StandardCp(ModeBaseCp):
    """mode standard en creation de plateau"""
    def __init__(self, plateau):
        super(StandardCp, self).__init__(plateau)
        self._sourceCurseur = ""
        self._focus = False
        self._activerDragMode = True

    def clic_combattant(self, num):
        self.plateau.activerMode(DeplacementPion, num)
        
    def clic_decor(self, num):
        self.plateau.activerMode(DeplacementPion, num)
        
class MajCases(ModeBaseCp):
    """mode de mise a jour des cases (terrain, couleur, effet special)"""
    def __init__(self, plateau):
        super(MajCases, self).__init__(plateau)
        self._sourceCurseur = "img\\curseurPinceau.png"
        self._focus = True
        self._param = None   #parametre avec lequel on mettra a jour la case

    def activer(self, param):
        """active le mode"""
        self.majParam(param)
        super(MajCases, self).activer()

    def desactiver(self):
        """desactive le mode"""
        self.plateau.pinceau.reinit()
        super(MajCases, self).desactiver()

    def majParam(self, param):
        self._param = param

    def param(self):
        return self._param

    def clic_case(self, coord):
        #demarre une operation de peinture des cases
        self.plateau.pinceau.demarrer(coord)

    def survolClic_case(self, coord):
        self.plateau.pinceau.maj(coord)

    def finClicGauche(self, event):
        if self.plateau.pinceau.estActif():
            for coord in self.plateau.pinceau.selection():
                self.plateau.cases[coord].majTerrain(self._param)
                self.plateau.pinceau.reinit()
            self.reinit()

    def toucheClavier(self, event):
        if event.key() == Qt.Key_Up:
            self.plateau.fenetre.ui.epaisseurPinceau.setValue(self.plateau.fenetre.ui.epaisseurPinceau.value()+1)
        elif event.key() == Qt.Key_Down:
            self.plateau.fenetre.ui.epaisseurPinceau.setValue(self.plateau.fenetre.ui.epaisseurPinceau.value()-1)

class MajCasesEffet(MajCases):
    """mode de mise a jour des cases (effets speciaux)"""
    def __init__(self, plateau):
        super(MajCasesEffet, self).__init__(plateau)    

    def finClicGauche(self, event):
        if self.plateau.pinceau.estActif():
            for coord in self.plateau.pinceau.selection():
                self.plateau.cases[coord].majEffet(self._param)
                self.plateau.pinceau.reinit()
            self.reinit()

class Pipette(ModeBaseCp):
    """mode pipette: on preleve la couleur ou le terrain d'une case"""
    def __init__(self, plateau):
        super(Pipette, self).__init__(plateau)
        self._sourceCurseur = "img\\curseurSeringue.png"

    def activerCurseur(self):
        super(Pipette, self).activerCurseur()
        
    def clic_case(self, coord):
        if len(self.plateau.cases[coord].terrain.nom) > 0:
             param = self.plateau.cases[coord].terrain
        else:
             param = self.plateau.cases[coord].couleur
        self.plateau.activerMode(MajCases, param)     
             

class ZonePlacement(ModeBaseCp):
    """mode de definition de la/les zones de placement des joueurs"""
    def __init__(self, plateau):
        super(ZonePlacement, self).__init__(plateau)
        self._sourceCurseur = "img\\curseurPinceau.png"
        self._focus = True

    def activerCurseur(self):
        super(ZonePlacement, self).activerCurseur()

    def activer(self, param = None):
        self.plateau.pinceau.majForme("rectP")
        self.plateau.pinceau.verrouillerForme(True)
        super(ZonePlacement, self).activer()

    def desactiver(self):
        self.plateau.pinceau.reinit()
        super(ZonePlacement, self).desactiver()

    def clic_case(self, coord):
        #demarre une operation de peinture des cases
        self.plateau.pinceau.demarrer(coord)
        
    def survolClic_case(self, coord):
        self.plateau.pinceau.maj(coord)
    
    def finClicGauche(self, coord):
        if self.plateau.pinceau.estActif():
            if len(self.plateau.pinceau.selection()) > 0:
                self.plateau.majZonePlacement(self.plateau.pinceau.selection())
                

class EntreesSorties(ModeBaseCp):
    """mode de definition deentrees et sorties du plateau"""
    def __init__(self, plateau):
        super(EntreesSorties, self).__init__(plateau)
        self._sourceCurseur = "img\\curseurPinceau.png"
        self._focus = True

    def activerCurseur(self):
        super(EntreesSorties, self).activerCurseur()

    def activer(self, param):
        self.es = param
        self.es.creerForme()
        super(EntreesSorties, self).activer()

    def desactiver(self):
        if not self.es.estPositionne:
            self.es.prepareGeometryChange()
            self.es.plateau = None
            self.plateau.removeItem(self.es)
        super(EntreesSorties, self).desactiver()
        
    def mouvementSouris(self, event):
        if event.buttons() != Qt.LeftButton:
            if not self.es.estPositionne:
                self.es.majProjection(event.scenePos())

    def clicGauche(self, event):
        if not event.isAccepted():
            self.es.positionner()
            self.plateau.entreesSorties.append(self.es)
            self.desactiver()

    def toucheClavier(self, event):
        if event.key() == Qt.Key_Delete:
            #supprimer l'es
            self.desactiver()
        elif event.key() == Qt.Key_Right:
            self.es.nbRotations += 1
            self.es.majProjection()   
        elif event.key() == Qt.Key_Left:
            self.es.nbRotations -= 1
            self.es.majProjection()    


class CreationPion(ModeBaseCp):
    """mode de creation de pions (combattant ou decor)"""
    def __init__(self, plateau):
        super(CreationPion, self).__init__(plateau)
        self._focus = True
        self._pion = None

    def activer(self, pion):
        self._pion = pion
        self.plateau.proj.creer(self._pion)
        super(CreationPion, self).activer()
        
    def desactiver(self):
        self.plateau.proj.desactiver()
        self._pion = None
        super(CreationPion, self).desactiver()

    def survol_case(self, coord):
        if self._pion:
            self.plateau.proj.majCoord(coord)

    def clic_case(self, coord):
        if self._pion:
            if not self.plateau.cases[coord].pionOccupant():
                self.plateau.creerPion(self._pion)

    def toucheClavier(self, event):
        if self._pion:
            if event.key() == Qt.Key_Right:
                self.plateau.proj.majRotation(1)
            elif event.key() == Qt.Key_Left:
                self.plateau.proj.majRotation(-1)


class SuppressionPion(ModeBaseCp):
    """mode de suppression de pions (combattant ou decor)"""
    def __init__(self, plateau):
        super(SuppressionPion, self).__init__(plateau)
        self._sourceCurseur = "img\\gomme.png"
        self._focus = True

    def clicGauche(self, event):
        """supprime le pion sous le clic. S'il y en a plusieurs,
            supprime le premier de la pile"""
        item = self.plateau.itemAt(event.scenePos())
        
        if item.parentItem().__class__.__name__ in ["Combattant", "Decor"]:
            self.plateau.pionSupprimer(item.parentItem().numero)
            

class DeplacementPion(ModeBaseCp):
    """mode de deplacement de pions (combattant ou decor) en mode creation
        attention: different des actions de type deplacement qu'effectuent les pions en mode Combat"""
    def __init__(self, plateau):
        super(DeplacementPion, self).__init__(plateau)
        self._num = 0
        
    def activer(self, num):
        self._num = num
        if self._num < 10000:
            pion = self.plateau.combattants[self._num]
        else:
            pion = self.plateau.decors[self._num]
        self.plateau.proj.creer(pion)
        self.deplace = False
        super(DeplacementPion, self).activer()

    def desactiver(self):
        self.plateau.proj.desactiver()
        self._num = 0
        super(DeplacementPion, self).desactiver()

    def survol_case(self, coord):
        if self._num > 0:
            self.plateau.proj.majCoord(coord)
            self.deplace = True

    def clic_case(self, coord):
        if self._num > 0:
            if self.deplace:
                if self._num < 10000:
                    pion = self.plateau.combattants[self._num]
                else:
                    pion = self.plateau.decors[self._num]
                pion.majPosition(self.plateau.proj.coord(), self.plateau.proj.nbRotations())

    def toucheClavier(self, event):
        if self._num > 0:
            if event.key() == Qt.Key_Right:
                self.plateau.proj.majRotation(1)
                self.deplace = True
            elif event.key() == Qt.Key_Left:
                self.plateau.proj.majRotation(-1)
                self.deplace = True


#-----------------------------------------------
#-----------------------------------------------

class StandardPi(ModeBasePi):
    """mode standard de la manipulation de pion en combat"""
    def __init__(self, plateau):
        super(StandardPi, self).__init__(plateau)
        self._focus = False
        self._activerDragMode = True

    def clic_combattant(self, num):
        self.plateau.activerMode(PionSelectionne, num)

    def nouvelleAction(self, action):
        pass

    
class PionSelectionne(ModeBasePi):
    """mode active a la selection d'un pion combattant"""
    def __init__(self, plateau):
        super(PionSelectionne, self).__init__(plateau)
        self._focus = True
        self._num = None
        self._action = None

    def pion(self):
        """retourne la ref du pion actuellement selectionne"""
        retour = None
        if self._num in self.plateau.combattants:
            retour = self.plateau.combattants[self._num]
        return retour

    def activer(self, num):
        self._num = num
        #intensifie l'ombre du pion
        self.pion().afficheOmbreSelection(True)
        self.plateau.majPanneauPi()
        super(PionSelectionne, self).activer()

    def desactiver(self):
        if self._action:
            self._action.desactiver()
            self._action = None
        self.pion().afficheOmbreSelection(False)
        self._num = None
        self.plateau.majPanneauPi()
        super(PionSelectionne, self).desactiver()

    def nouvelleAction(self, action):
        if self._action:
            self._action.desactiver()
            self._action = None            
        self._action = action()
        self._action.activer(self.plateau, self._num)
        
    def survol_case(self, coord):
        if self._action:
            self._action.majCoordCible(coord)

    def clic_case(self, coord):
        if self._action:
            terminee = self._action.valider()
            if not self._action.enCours(): self._action = None
           
    def clicDroit(self, event):
        if self._action != None:
            self._action.desactiver()
            self._action = None
        else:
            super(PionSelectionne, self).clicDroit(event)

    def toucheClavier(self, event):
        if self._num > 0:
            if event.key() == Qt.Key_Right:
                self._action.pivoter(1)
            elif event.key() == Qt.Key_Left:
                self._action.pivoter(-1)



        
