# -*- coding: latin1 -*-
# Import the PyQt and QGIS libraries
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
import math


# 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
    
    
# 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 QgsRasterLayer from a layer name ( as string )
def getRasterLayerByName( myName ):
    layermap = QgsMapLayerRegistry.instance().mapLayers()
    for name, layer in layermap.iteritems():
        if layer.type() == QgsMapLayer.RasterLayer and layer.name() == myName:
            if layer.isValid():
                return layer
            else:
                return None                    
                
# Return LayerType  from a layer name.
# 0: vector layer
# 1: raster layer
def getLayerTypeByName( myName ):
    layermap = QgsMapLayerRegistry.instance().mapLayers()
    for name, layer in layermap.iteritems():
        if layer.name() == myName:
            return layer.type()
    
                
# Return the field list of a vector layer
# (c) Carson Farmer / fTools
def getFieldList( vlayer ):
    vprovider = vlayer.dataProvider()
    feat = QgsFeature()
    allAttrs = vprovider.attributeIndexes()
    vprovider.select( allAttrs )
    myFields = vprovider.fields()
    return myFields                


