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

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class VueEditionForme(QGraphicsScene):
    """vue graphique permettant d'afficher et de modifier la forme des creatures/decors"""
    def __init__(self, fenetre, formeCases="H", parent=None):   
        super(VueEditionForme, self).__init__()
        self.fenetre = fenetre
        self.pixGraphique = None
        self.text = None
        self.largeurOriginale = 0
        self.hauteurOriginale = 0
        self.rotation = 0
        self.cases = {}
        self.formeCases = formeCases

    def creer(self):
        #cree les cases hexagonales
        for x in range(-5,6):
            for y in range(-5,6):
                if self.formeCases == "H":
                     if 1 == (x % 2):
                          y += 0.5
                c = CaseEditionForme(self)
                c.creer(x, y, self.formeCases)
                self.cases[(x,y)] = c
                
        self.fenetre.ui.vueForme.setScene(self)    
        self.fenetre.ui.vueForme.centerOn(self.fenetre.ui.vueForme.mapFromScene(QPointF(60,60)))   #centre la vue sur la case 0,0
        self.fenetre.ui.vueForme.scale(0.25, 0.25)
        

    def formeDef(self):
        """liste definissant la forme"""
        retour = []
        for coord in self.cases:
            if self.cases[coord].estSelectionnee and coord != (0,0):
                retour.append(coord)      
        return retour        

    def majForme(self, formeDef):
        """met a jour la forme sur le graphique"""
        if formeDef:
            for coord in formeDef:
                if coord in self.cases:
                    self.cases[coord].estSelectionnee = True
                    self.cases[coord].setBrush(QColor("red"))

    def majTexte(self, txt, taillePolice = 20, gras = False, dx = 0, dy = 0, rotation = 0):
        if len(txt) > 0:
            if not self.text:
                self.text = QGraphicsSimpleTextItem()
                self.addItem(self.text)
            self.text.setText(QString.fromUtf8("1."+txt))
            self.text.setPos(QPointF(dx-0.112*120, dy-0.275*120))
            police = QFont("Georgia", taillePolice)
            police.setBold(gras)
            self.text.setFont(police)
            self.text.setRotation(rotation)
        else:
            if self.text:
                self.removeItem(self.text)

    def majImage(self, img, kx = 10, ky = 10, dx = 0, dy = 0, rotation = 0, imgPivote = False, masqueAuto = False):
        if len(img) > 0:
            pix = QPixmap(QString.fromUtf8("img\\"+img))
            if not pix.isNull():
                if masqueAuto == True:
                    pix.setMask(pix.createHeuristicMask())
                if not self.pixGraphique:
                    self.pixGraphique = QGraphicsPixmapItem()
                    self.addItem(self.pixGraphique)
                    self.pixGraphique.setZValue(10)
                    if pix.height() >= pix.width():
                        pix = pix.scaledToHeight(120*0.9, Qt.SmoothTransformation)
                    else:
                        pix = pix.scaledToWidth(120*0.9, Qt.SmoothTransformation)
                    self.largeurOriginale = pix.width()
                    self.hauteurOriginale = pix.height()    

                pix = pix.scaled((kx/10)*self.largeurOriginale, (ky/10)*self.hauteurOriginale, Qt.IgnoreAspectRatio, Qt.SmoothTransformation)
                deltaX = dx + 0.5*(120*1.1544 - self.largeurOriginale)
                deltaY = dy + 0.5*(120 - self.hauteurOriginale)
      
                self.pixGraphique.setPixmap(pix)    
                self.pixGraphique.setPos(QPointF(deltaX, deltaY))
                self.pixGraphique.setRotation(rotation)
        else:
            if self.pixGraphique:
                self.removeItem(self.pixGraphique)

    def majSelection(self, coord):
         """met a jour l'affichage des cases selectionnees pour l'affichage de la forme"""
         if self.cases[coord].estSelectionnee == True:
             self.cases[coord].estSelectionnee = False
             valide = True
             for coordVerif in self.cases:
                 #on parcourt les autres cases selectionnees
                 if coordVerif != (0,0) and coordVerif != coord and self.cases[coordVerif].estSelectionnee == True:
                     #on liste les cases connectees a cette case, de proche en proche
                     connectees = [coordVerif]
                     for coordVerif2 in connectees:
                         for coordVoisin in self.cases[coordVerif2].voisins:
                             if coordVoisin in self.cases and not coordVoisin in connectees:
                                 if self.cases[coordVoisin].estSelectionnee:
                                     connectees.append(coordVoisin)
                     if not (0,0) in connectees:
                         valide = False
                         break
             if valide == True:        
                 self.cases[coord].setBrush(QColor("white"))
             else:
                 self.cases[coord].estSelectionnee = True
         else:
             #on s'assure que la case est bien adjacente a une case selectionnee
             valide = False
             for coordVerif in self.cases[coord].voisins:
                if coordVerif in self.cases:
                    if self.cases[coordVerif].estSelectionnee == True:
                        valide = True
                        break
             if valide:
                 self.cases[coord].estSelectionnee = True
                 self.cases[coord].setBrush(QColor("red"))

class CaseEditionForme(QGraphicsPolygonItem):
    """case utilisee dans une VueEditionForme()"""
    def __init__(self, vueForme, parent=None):
        super(CaseEditionForme, self).__init__()
        self.vue = vueForme
        self.position = (0,0)
        self.estSelectionnee = False
        self.voisins = []
        
        #interactions graphiques
        self.setFlag(QGraphicsItem.ItemIsFocusable)
        self.setAcceptHoverEvents(True)
        #self.setAcceptDrops(True)

    def creer(self, x, y, formeCases="H"):
        """creation du polygone et enregistrement des donnees geometriques"""
        self.position = (x, y)
        polygone = QPolygonF()
        if self.vue.formeCases == "H":
            polygone  << QPointF(((x*0.866)+0.2886)*120,  y*120) \
                      << QPointF(((x*0.866)+0.866)*120,   y*120) \
                      << QPointF(((x*0.866)+1.1547)*120, (y+0.5)*120) \
                      << QPointF(((x*0.866)+0.866)*120,  (y+1)*120) \
                      << QPointF(((x*0.866)+0.2886)*120, (y+1)*120)  \
                      << QPointF( (x*0.866)*120,         (y+0.5)*120)
        else:
            polygone  << QPointF(x*120,      y*120) \
                      << QPointF((x+1)*120,  y*120) \
                      << QPointF((x+1)*120,  (y+1)*120) \
                      << QPointF(x*120,      (y+1)*120)          
        self.setPolygon(polygone)

        #enregistrement des cases voisines:       
        if self.vue.formeCases == "H":
            self.voisins.append((x, y+1))
            self.voisins.append((x, y-1))
            self.voisins.append((x-1, y+0.5))
            self.voisins.append((x-1, y-0.5))
            self.voisins.append((x+1, y+0.5))
            self.voisins.append((x+1, y-0.5))
        else:
            self.voisins.append((x,   y-1))
            self.voisins.append((x,   y+1))
            self.voisins.append((x-1, y))
            self.voisins.append((x+1, y))

        #pour afficher les coordonnees des cases:        
        #text = QGraphicsSimpleTextItem("{}-{}".format(x,y), parent=self)
        #police = QFont()
        #police.setPointSize(20)
        #text.setFont(police)
        #text.setPos(QPointF(((x*0.866)+0.2886)*120,  y*120))

        #couleur de fond par defaut
        if self.position == (0, 0):
            self.setBrush(QColor("purple"))
            self.estSelectionnee = True
        else:    
            self.setBrush(QColor("white"))
        #creation de l'objet graphique sur le plateau
        self.vue.addItem(self)

    def mousePressEvent(self, event):
        """evenement lors du clic souris"""
        super(CaseEditionForme, self).mousePressEvent(event)
        if event.button() == 1: #sur clic gauche
            if self.position != (0, 0):
                self.vue.majSelection(self.position)             
