# -*- coding: utf8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtXml
from qgis.core import *
from qgis.gui import *
from helmert2d.tools.point import Point

# Returns a vector layer with the transformed control points.
def createTransformationVectorFieldLayer(controlpoints):
        memlayer = QgsVectorLayer("Point", "Control points vector field", "memory")
        qml = QDir.convertSeparators(QDir.cleanPath(QgsApplication.qgisSettingsDirPath() + '/python/plugins/helmert2d/styles/vectors.qml'))
        memlayer.loadNamedStyle(qml)            
        memprovider = memlayer.dataProvider()
        
        fields = [ QgsField("gcp", QVariant.String),
                  QgsField("xlocal", QVariant.Double), 
                  QgsField("ylocal", QVariant.Double), 
                  QgsField("xglobal", QVariant.Double), 
                  QgsField("yglobal", QVariant.Double), 
                  QgsField("xtrans", QVariant.Double), 
                  QgsField("ytrans", QVariant.Double), 
                  QgsField("vx", QVariant.Double),        
                  QgsField("vy", QVariant.Double)]        
        
        memprovider.addAttributes( fields )
        memlayer.updateFieldMap()

        for controlpoint in controlpoints:
            if controlpoint.isChecked() == False:
                continue
                
            feat = QgsFeature()
            
            gcp = controlpoint.getIdent()
            xlocal = float(controlpoint.getXlocal())
            ylocal = float(controlpoint.getYlocal())
            xglobal = float(controlpoint.getXglobal())
            yglobal = float(controlpoint.getYglobal())
            xtrans = float(controlpoint.getXtrans())
            ytrans = float(controlpoint.getYtrans())
            vx = (xtrans - xglobal)*1000
            vy = (ytrans - yglobal)*1000
            
            feat.setGeometry(QgsGeometry().fromPoint(QgsPoint(xglobal, yglobal)))            
            
            feat.addAttribute(0, QVariant(gcp))
            feat.addAttribute(1, QVariant(xlocal))
            feat.addAttribute(2, QVariant(ylocal))
            feat.addAttribute(3, QVariant(xglobal))
            feat.addAttribute(4, QVariant(yglobal))
            feat.addAttribute(5, QVariant(xtrans))
            feat.addAttribute(6, QVariant(ytrans))
            feat.addAttribute(7, QVariant(vx))
            feat.addAttribute(8, QVariant(vy))
            
            memprovider.addFeatures( [ feat ] )

        return memlayer


# Returns List of the control points
def getControlPointsFromVectorLayer(globalLayer, localLayer, globalIdent, localIdent):
    globalLayerProvider = globalLayer.dataProvider()
    globalFeature= QgsFeature()
    allAttrsGlobal = globalLayerProvider.attributeIndexes()
    globalLayerProvider.select(allAttrsGlobal)

    localLayerProvider = localLayer.dataProvider()
    localFeature= QgsFeature()
    allAttrsLocal = localLayerProvider.attributeIndexes()
    localLayerProvider.select(allAttrsLocal)
    
    identGlobalIdx = globalLayerProvider.fieldNameIndex(globalIdent)
    identLocalIdx = localLayerProvider.fieldNameIndex(localIdent)    
    
    if identGlobalIdx == -1:
        QMessageBox.warning( None, "Helmert2d", "Attribute (<i>"+globalIdent+"</i>) in global layer not found." )
        return 

    if identLocalIdx == -1:
        QMessageBox.warning( None, "Helmert2d", "Attribute (<i>"+localIdent+"</i>) in local layer not found." )
        return 
    
    controlpoints = []
    
    while globalLayerProvider.nextFeature(globalFeature):
        globalGeom = globalFeature.geometry()
        identAttrGlobal = str(globalFeature.attributeMap()[identGlobalIdx].toString()).strip()

        while localLayerProvider.nextFeature(localFeature):
            localGeom = localFeature.geometry()
            identAttrLocal = str(localFeature.attributeMap()[identLocalIdx].toString()).strip()

            if identAttrGlobal == identAttrLocal:
                gcp = Point(str(identAttrGlobal))
                gcp.setXglobal(globalGeom.asPoint().x())
                gcp.setYglobal(globalGeom.asPoint().y())
                gcp.setXlocal(localGeom.asPoint().x())
                gcp.setYlocal(localGeom.asPoint().y())
                
                controlpoints.append(gcp)
                break

    return controlpoints


# Return QgsVectorLayer from a layer name ( as string )
# (c) Carson Farmer / fTools
def getVectorLayerByName( myName ):
    layermap = QgsMapLayerRegistry.instance().mapLayers()
    for name, layer in layermap.iteritems():
        if layer.type() == QgsMapLayer.VectorLayer and layer.name() == myName:
            if layer.isValid():
                return layer
            else:
                return None    


# Return list of names of all layers in QgsMapLayerRegistry
# (c) Carson Farmer / fTools
def getLayerNames( vTypes,  providerException=None ):
    layermap = QgsMapLayerRegistry.instance().mapLayers()
    layerlist = []
    if vTypes == "all":
        for name, layer in layermap.iteritems():
            provider = layer.dataProvider()
            ## Is this a bug??? I only get "None" as provider for a TIFF....???
            if provider == None:
                layerlist.append( unicode( layer.name() ) )
                continue
            providerName = provider.name()
            if providerName == providerException:
                continue
            else:
                layerlist.append( unicode( layer.name() ) )
    else:
        for name, layer in layermap.iteritems():
            if layer.type() == QgsMapLayer.VectorLayer:
                if layer.geometryType() in vTypes:
                    layerlist.append( unicode( layer.name() ) )
            elif layer.type() == QgsMapLayer.RasterLayer:
                if "Raster" in vTypes:
                    layerlist.append( unicode( layer.name() ) )
    return layerlist
