#!/usr/bin/env python
import sys
import platform
from PyQt4.QtCore import *
from PyQt4.QtGui import *

from data_ui import Ui_Form
import os
from grass.script.core import *
from g2k import GrassToKml
from vrt import VrtG
iconpath = ""
extrudetype = ""
AltitudeMode = ""
HeightColumn = ""
AttributeList = ""
VectorLineColorName = ""
VectorLabelColorName = ""
VectorPolygonColorName = ""

grassenv = gisenv()
rasterpath = grassenv['GISDBASE']+'/'+grassenv['LOCATION_NAME']+'/'+ \
           grassenv['MAPSET']+'/cellhd/'
vectorpath = grassenv['GISDBASE']+'/'+grassenv['LOCATION_NAME']+'/'+ \
           grassenv['MAPSET']+'/vector/'

apppath = os.path.abspath(os.path.dirname(sys.argv[0]))

kmlfile = '%s/gps/nmea.kml' % (apppath)
imagepath = '%s/icons/' % (apppath)
vrtpath = '%s/vrt/' % (apppath)


class Data(QWidget, Ui_Form):
    def __init__(self):
        QWidget.__init__(self)
        self.setupUi(self)
        self.vrt = VrtG()
        self.raster = self.RasterList()
        self.vector = self.VectorList()
        self.InputRaster.addItems(self.raster)
        self.InputVector.addItems(self.vector)
        #self.InputLayer.addItems(self.raster)
        self.Tile.setText("0")
        self.connect(self.InputVector, SIGNAL("currentIndexChanged(int)"),
                     self.GetAttribute)
        #self.connect(self.GrassType, SIGNAL("currentIndexChanged(int)"),
        #             self.GetType)
        #self.connect(self.GrassLayer, SIGNAL("currentIndexChanged(int)"),
        #             self.GetLayer)
        self.connect(self.LabelAlpha, SIGNAL("valueChanged(double)"), 
                     self.SetLabelAlpha)
        self.connect(self.LineAlpha, SIGNAL("valueChanged(double)"), 
                     self.SetLineAlpha)
        self.connect(self.PolygonAlpha, SIGNAL("valueChanged(double)"), 
                     self.SetPolygonAlpha)
        self.connect(self.LineWidth, SIGNAL("valueChanged(double)"), 
                     self.SetLineWidth)
        self.connect(self.Offset, SIGNAL("valueChanged(double)"), 
                     self.SetOffset)
        self.connect(self.InputRaster, SIGNAL("currentIndexChanged(int)"),
                     self.GetTile)
        self.connect(self.ExportElev, SIGNAL("clicked()"), 
                     self.ExportElevation)
        self.connect(self.ExportVect, SIGNAL("clicked()"), 
                     self.setKmlInput)
        self.connect(self.VectorLabelColor, SIGNAL("clicked()"), 
                     self.setVectorLabelColor)
        self.connect(self.VectorLineColor, SIGNAL("clicked()"), 
                     self.setVectorLineColor)
        self.connect(self.VectorPolygonColor, SIGNAL("clicked()"), 
                     self.setVectorPolygonColor)
        self.connect(self.SelectIcon, SIGNAL("currentIndexChanged(int)"),
                     self.GetIcon)
        self.connect(self.ExtrudeType, SIGNAL("currentIndexChanged(int)"),
                     self.GetExtrudeType)
        self.connect(self.AltitudeMode, SIGNAL("currentIndexChanged(int)"),
                     self.GetAltitudeMode)
        self.connect(self.colorModeEnum, SIGNAL("currentIndexChanged(int)"),
                     self.GetColorMode)
        self.connect(self.HeightColumn, SIGNAL("currentIndexChanged(int)"),
                     self.GetHeightColumn)
        self.connect(self.AttributeList, SIGNAL("currentIndexChanged(int)"),
                     self.GetAttributeList)
        #self.connect(self.opendir, SIGNAL("clicked()"),
        #             self.filemanager)
        #self.connect(self.ExportImage, SIGNAL("clicked()"),
        #             self.vrtdata) 


    def vrtdata(self):
        self.vrt.show()

    def SetLabelAlpha(self, ap):
        self.labelalpha = int(ap)
        self.LabelAlpha.setRange(0, 255)
        self.LabelAlpha.setValue(self.labelalpha)

    def SetLineAlpha(self, ap):
        self.linealpha = int(ap)
        self.LineAlpha.setRange(0, 255)
        self.LineAlpha.setValue(self.linealpha)

    def SetPolygonAlpha(self, ap):
        self.polygonalpha = int(ap)
        self.PolygonAlpha.setRange(0, 255)
        self.PolygonAlpha.setValue(self.polygonalpha)

    def SetLineWidth(self, wd):
        self.linewidth = int(wd)
        self.LineWidth.setRange(0, 99)
        self.LineWidth.setValue(self.linewidth)

    def SetOffset(self, ofst):
        self.offset = float(ofst)
        self.Offset.setRange(-10000, 1000000)
        self.Offset.setValue(self.offset)


    def VectorList(self):
        global vector
        v = list_strings('vect')
        vector = []
        for i in v:
            vname = i.split('@', 2)[0]
            vector.append(vname)
        vector.sort()
        return vector

    def RasterList(self):
        global raster
        r = list_strings('rast')
        raster = []
        for i in r:
            rname = i.split('@', 2)[0]
            raster.append(rname)
        raster.sort()
        return raster

    def RegionList(self):
        global region
        rg = list_strings('region')
        region = []
        for i in rg:
            rgname = i.split('@', 2)[0]
            region.append(rgname)
        region.sort()
        return region

    def GetType(self,index):
        Gtype = self.GrassType.itemText(index)
        if Gtype == 'region':
            rg = list_strings('region')
            region = []
            for i in rg:
                rgname = i.split('@', 2)[0]
                region.append(rgname)
            self.InputType.clear()
            self.InputType.addItems(region)
        if Gtype == 'vector':
            vc = list_strings('vect')
            vector = []
            for i in vc:
                vecname = i.split('@', 2)[0]
                vector.append(vecname)
            self.InputType.clear()
            self.InputType.addItems(vector)
        if Gtype == 'raster':
            rs = list_strings('rast')
            raster = []
            for i in rs:
                rasname = i.split('@', 2)[0]
                raster.append(rasname)
            self.InputType.clear()
            self.InputType.addItems(raster)


    def GetLayer(self,index):
        GLayer = self.GrassLayer.itemText(index)
        if GLayer == 'vector':
            vc = list_strings('vect')
            vector = []
            for i in vc:
                vecname = i.split('@', 2)[0]
                vector.append(vecname)
            self.InputLayer.clear()
            self.InputLayer.addItems(vector)
        if GLayer == 'raster':
            rs = list_strings('rast')
            raster = []
            for i in rs:
                rasname = i.split('@', 2)[0]
                raster.append(rasname)
            self.InputLayer.clear()
            self.InputLayer.addItems(raster)

    def GetAttribute(self,index):
        global inputvector
        attr = []
        infile = self.InputVector.itemText(index)
        inputvector = vectorpath+infile+str('/head')
        s = read_command('v.info', map=infile, flags='c') 
        attr = parse_key_val(s,'|')
        attr = attr.values()
        self.AttributeList.clear()
        self.AttributeList.addItems(attr)
        self.HeightColumn.clear()
        self.HeightColumn.addItems(attr)


    def GetAttributes(self,index):
        infile = self.InputVector.itemText(index)
        infile = str(vectorpath)+str(infile)+str('/')+str('head')
        #print infile
        in_ds = ogr.Open( infile, update = 1 )
        in_layer = in_ds.GetLayer(1)
        attr = in_layer.GetLayerDefn().GetFieldCount()
        print attr
        attributi = []
        for i in range(attr):
            attname = in_layer.GetLayerDefn().GetFieldDefn(i).GetName()
            attributi.append(attname)
        print attributi


    def GetTile(self,index):
        global tiling
        global inputfile
        inputfile = self.InputRaster.itemText(index)
        res = read_command("r.info", map=inputfile, flags='s')
        res = parse_key_val(res, '=')
        ewres = float(res['ewres'])
        nsres = float(res['nsres'])
        tiling = ((108000 + nsres) / ewres )
        print tiling

    def setSaveRaster(self):
        SaveRaster = QFileDialog.getSaveFileName()
        if not SaveRaster.isEmpty():
            self.saveFileNameLabel.setText(SaveRaster)

    def setLoadRaster(self):
        InputRaster = QFileDialog.getOpenFileName()
        if not InputRaster.isEmpty():
            self.LoadRasterLabel.setText(InputRaster)

    def setKmlInput(self):
        tessellate = 0
        extrude = 0
        if self.Tessellate.isChecked():
            tessellate = 1
        if self.Extrude.isChecked():
            extrude = 1
        ExportVector = QFileDialog.getSaveFileName()
        if self.Point.isChecked():
            print extrudetype,'point', inputvector, ExportVector, 1, 'name', 0,\
                  'some desription here', VectorLabelColorName, 'labelscale', \
                  iconpath, tessellate, extrude, self.LineWidth.value(), \
                  VectorLineColorName, colormode, VectorPolygonColorName, \
                  AttributeList, 0, 0, 0, 0, 0, AltitudeMode, \
                  self.Offset.value(), HeightColumn, \
                  self.LabelAlpha.value(), self.LineAlpha.value(), \
                  self.PolygonAlpha.value()
            GrassToKml(extrudetype,'point', inputvector, ExportVector, 1, 
                       'name', 0, 'some desription here', VectorLabelColorName, 
                       'labelscale', iconpath, tessellate, extrude, 
                       self.LineWidth.value(), VectorLineColorName, colormode, 
                       VectorPolygonColorName, AttributeList, 0, 0, 0, 0, 0, 
                       AltitudeMode, self.Offset.value(), HeightColumn, 
                       self.LabelAlpha.value(), self.LineAlpha.value(), 
                       self.PolygonAlpha.value())

        if self.Line.isChecked():
            print extrudetype,'line', inputvector, ExportVector, 1, \
                       'name', 0, 'some desription here', VectorLabelColorName, \
                       'labelscale', iconpath, tessellate, extrude, \
                       self.LineWidth.value(), VectorLineColorName, colormode, \
                       VectorPolygonColorName, AttributeList, 0, 0, 0, 0, 0, \
                       AltitudeMode, self.Offset.value(), HeightColumn, \
                       self.LabelAlpha.value(), self.LineAlpha.value(), \
                       self.PolygonAlpha.value()
            GrassToKml(extrudetype,'line', inputvector, ExportVector, 1, 
                       'name', 0, 'some desription here', VectorLabelColorName, 
                       'labelscale', iconpath, tessellate, extrude, 
                       self.LineWidth.value(), VectorLineColorName, colormode, 
                       VectorPolygonColorName, AttributeList, 0, 0, 0, 0, 0, 
                       AltitudeMode, self.Offset.value(), HeightColumn, 
                       self.LabelAlpha.value(), self.LineAlpha.value(), 
                       self.PolygonAlpha.value())
        if self.Polygon.isChecked():
            print extrudetype,'polygon', inputvector, ExportVector, 2, \
                  'name', 0, 'some desription here', VectorLabelColorName, \
                  'labelscale', iconpath, tessellate, extrude, \
                  self.LineWidth.value(), VectorLineColorName, colormode, \
                  VectorPolygonColorName, AttributeList, 0, 0, 0, 0, 0, \
                  AltitudeMode, self.Offset.value(), HeightColumn, \
                  self.LabelAlpha.value(), self.LineAlpha.value(), \
                  self.PolygonAlpha.value()
            GrassToKml(extrudetype,'polygon', inputvector, ExportVector, 1, 
                       'name', 0, 'some desription here', VectorLabelColorName, 
                       'labelscale', iconpath, tessellate, extrude, 
                       self.LineWidth.value(), VectorLineColorName, colormode, 
                       VectorPolygonColorName, AttributeList, 0, 0, 0, 0, 0, 
                       AltitudeMode, self.Offset.value(), HeightColumn, 
                       self.LabelAlpha.value(), self.LineAlpha.value(), 
                       self.PolygonAlpha.value())

    def ExportElevation(self):
        ExportElev = QFileDialog.getSaveFileName()
        outname = ExportElev.split('/')[-1]
        if self.ManualTiling.isChecked():
            tile = self.Tile.text()
            start_command("g.ossim", flags = '1a' , elevation = inputfile , 
                          tiling = tile , directory = ExportElev , name = outname)
        if self.Autotiling.isChecked():
            start_command("g.ossim", flags = '1b' , elevation = inputfile , 
                          directory = ExportElev , name = outname)

    def setVectorLineColor(self):
        global VectorLineColor
        global VectorLineColorName
        VectorLineColor = QColorDialog.getColor()
        VectorLineColorName = VectorLineColor.name()
        if VectorLineColor.isValid():
            self.LineColor.setStyleSheet("QWidget { background-color: %s }"
                                           % VectorLineColor.name() )
            return VectorLineColor.name()
        return VectorLineColorName

    def setVectorLabelColor(self):
        global VectorLabelColor
        global VectorLabelColorName
        VectorLabelColor = QColorDialog.getColor()
        VectorLabelColorName = VectorLabelColor.name()
        if VectorLabelColor.isValid():
            self.LabelColor.setStyleSheet("QWidget { background-color: %s }"
                                            % VectorLabelColor.name() )
            return VectorLabelColor.name()
        return VectorLabelColorName

    def setVectorPolygonColor(self):
        global VectorPolygonColor
        global VectorPolygonColorName
        VectorPolygonColor = QColorDialog.getColor()
        VectorPolygonColorName = VectorPolygonColor.name()
        if VectorPolygonColor.isValid():
            self.PolyColor.setStyleSheet("QWidget { background-color: %s }"
                                           % VectorPolygonColor.name() )
            return VectorPolygonColor.name()
        return VectorPolygonColorName

    def GetIcon(self,index):
        global iconpath
        icon = self.SelectIcon.itemText(index)
        iconpath = imagepath+str(icon)+str('.png')
        return iconpath

    def GetExtrudeType(self, index):
        global extrudetype
        extrudetype = self.ExtrudeType.itemText(index)
        return extrudetype

    def GetAltitudeMode(self, index):
        global AltitudeMode
        AltitudeMode = self.AltitudeMode.itemText(index)
        return AltitudeMode

    def GetColorMode(self, index):
        global colormode
        colormode = self.colorModeEnum.itemText(index)
        return colormode

    def GetHeightColumn(self, index):
        global HeightColumn
        HeightColumn = self.HeightColumn.itemText(index)
        return HeightColumn

    def GetAttributeList(self, index):
        global AttributeList
        AttributeList = self.AttributeList.itemText(index)
        return AttributeList

    def WhichPlatform(self):
        #global platform
        platforms = platform.system()
        return platforms

    def filemanager(self):
        systemplatform = self.WhichPlatform()
        if systemplatform == 'Darwin':
            filemanager = 'open'
        else :
            for dirname in os.environ['PATH'].split(os.pathsep):
                if os.path.exists(os.path.join(dirname, 'thunar')):
                    filemanager = 'thunar'
                if os.path.exists(os.path.join(dirname, 'nautilus')):
                    filemanager = 'nautilus'
                if os.path.exists(os.path.join(dirname, 'konqueror')):
                    filemanager = 'konqueror'
        output = subprocess.Popen([filemanager ,str(vrtpath)], stdout=subprocess.PIPE).communicate()[0]
