# -*- coding: utf-8 -*-

from PyQt4.QtCore import *
from PyQt4.QtGui import *
import resources_rc
from qgis.core import *
import json,traceback, os, importlib, imp
from mapTools.VectorizeTool import VectorizeTool
from mapTools.VectorFixerTool import VectorFixerTool
from dialogs.SettingsDialog import SettingsDialog
from mapHelpers.MapGraph import MapGraph

class MagicWand(QObject):
    def __init__(self, iface):
        # save reference to the QGIS interface
        QObject.__init__(self)
        self.iface = iface
        self.legend = iface.legendInterface()
        self.canvas = iface.mapCanvas()
        self.vectorizeTool = None
        self.vectorFixerTool = None
        self.mapGraph = MapGraph()

    def initGui(self):
        self.tlbVectorizeTools = self.iface.addToolBar("MagicWand")
        self.dialogSettings = SettingsDialog(self.iface.mainWindow())
        self.dialogSettings.settingsChanged.connect(self.setChanged)

        self.labelColor = QLabel("     ")
        self.setLabelColor((255,255,255))
        self.tlbVectorizeTools.addWidget(self.labelColor)

        self.vectorizeAct = QAction("&Vectorize", self.iface.mainWindow())
        self.vectorizeAct.setIcon(QIcon(":/VectorizeTools/icons/magic_wand.png"))
        self.vectorizeAct.setEnabled(True)
        self.vectorizeAct.setCheckable(True)

        self.vectorFixerAct = QAction("&Fix vector", self.iface.mainWindow())
        self.vectorFixerAct.setIcon(QIcon(":/VectorizeTools/icons/magic_hat.png"))
        self.vectorFixerAct.setEnabled(True)
        self.vectorFixerAct.setCheckable(True)
        #self.vectorFixerAct.setVisible(False)

        self.settingsAct = QAction("&Settings", self.iface.mainWindow())
        self.settingsAct.setIcon(QIcon(":/VectorizeTools/icons/settings.png"))
        self.settingsAct.setEnabled(True)
        self.settingsAct.activated.connect(self.dialogSettings.show)

        self.iface.addPluginToMenu("VectorizeTools", self.vectorizeAct)
        self.iface.addPluginToMenu("VectorizeTools", self.vectorFixerAct)
        self.iface.addPluginToMenu("VectorizeTools", self.settingsAct)
        self.tlbVectorizeTools.addAction(self.vectorizeAct)
        self.tlbVectorizeTools.addAction(self.vectorFixerAct)
        self.tlbVectorizeTools.addAction(self.settingsAct)

        self.createMapTools()


    def setChanged(self, settings):
        self.vectorizeTool.reset()
        self.vectorFixerTool.reset()
        self.mapGraph.tolerance = settings["tolerance"]
        self.mapGraph.approximation = settings["approximation"]
        self.mapGraph.timeout = settings["timeout"]
        self.mapGraph.viewSteps = settings["viewSteps"]
        """self.vectorizeTool.setTolerance(settings["tolerance"])
        self.vectorizeTool.setTimeout(settings["timeout"])
        self.vectorizeTool.setApproximation(settings["approximation"])
        self.vectorizeTool.setViewSteps(settings["viewSteps"])"""

    def createMapTools(self):

        if self.vectorizeTool:
            self.vectorizeTool.reset()
        if self.vectorFixerTool:
            self.vectorizeTool.reset()

        self.vectorizeTool = VectorizeTool(
                 self.canvas,
                 self.iface,
                 self.mapGraph
                )
        self.vectorizeTool.setAction(self.vectorizeAct)
        self.vectorizeTool.pixelOver.connect(self.setLabelColor)
        self.vectorizeTool.vectorLayerRequired.connect(self.setTempLayer)
        self.vectorizeAct.triggered.connect(self.triggerMapTool)

        self.vectorFixerTool = VectorFixerTool(
                 self.canvas,
                 self.iface,
                 self.mapGraph
                )
        self.vectorFixerTool.setAction(self.vectorFixerAct)
        self.vectorFixerAct.triggered.connect(self.triggerMapTool)

    def triggerMapTool(self, activated):
        if activated: self.canvas.setMapTool(self.getToolFromAction(self.sender()))
        else: self.canvas.unsetMapTool(self.getToolFromAction(self.sender()))

    def getToolFromAction(self, action):
        if action == self.vectorizeAct: return self.vectorizeTool
        elif action == self.vectorFixerAct: return self.vectorFixerTool
        else: return None
    def unload(self):
        self.iface.removePluginMenu("MagicWand", self.vectorizeAct)
        self.iface.removePluginMenu("MagicWand", self.settingsAct)

    def setLabelColor(self, color):
        r,g,b = color
        self.labelColor.setStyleSheet("QLabel { background-color : rgb("+str(r)+","+str(g)+","+str(b)+"); border: 1px solid black; }")


    # ========================================= Temp layer ========================================= #

    def setTempLayer(self):
        if not self.vectorizeTool.tempVectorLayer or not self.vectorizeTool.tempVectorLayer.isValid():
            tempVectorLayer = QgsVectorLayer("Polygon", "temp", "memory")
            stylePath = os.path.dirname(os.path.abspath(__file__))
            stylePath = stylePath+os.path.sep+"styles"+os.path.sep+"vectorStyle.qml"
            tempVectorLayer.loadNamedStyle(stylePath)

            #QMessageBox.information(None, "", str(stylePath))
            results = QgsMapLayerRegistry.instance().addMapLayers([tempVectorLayer])

            if tempVectorLayer.isValid() and tempVectorLayer in results:
                self.vectorizeTool.tempVectorLayer = tempVectorLayer
            else:
                QMessageBox.information(None, "", "Cannot create vector layer")
