#!/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
import zipfile

iconpath = ""
iconspath = ""
extrudetype = ""
AltitudeMode = ""
HeightColumn = ""
AttributeList = ""
VectorLineColorName = ""
VectorLabelColorName = ""
VectorPolygonColorName = ""
BkgOvlColorName = ""

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.lon = 0
        self.lat = 0
        self.vrt = VrtG()
        self.raster = self.RasterList()
        self.vector = self.VectorList()
        self.InputRaster.addItems(self.raster)
        self.InputVector.addItems(self.vector)
        rast = len(self.raster)
        numrow = rast
        self.data.setColumnCount(1)
        self.data.setRowCount(numrow)
        self.data.setEditTriggers(QTableWidget.NoEditTriggers)
        for i in range(rast):
            item = QTableWidgetItem(raster[i])
            item.setTextAlignment(Qt.AlignCenter)
            item.setCheckState(Qt.Unchecked)
            self.data.setItem(i, 0, item)
        self.Tile.setText("0")
        self.connect(self.InputVector, SIGNAL("currentIndexChanged(int)"),
                     self.GetAttribute)
        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.kmlbkgcolor, SIGNAL("clicked()"), 
                     self.setkmlbkgcolor)
        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.textlegendcolor, SIGNAL("currentIndexChanged(int)"),
                     self.GetlegendColor)
        self.connect(self.TrueColor, SIGNAL("currentIndexChanged(int)"),
                     self.GetTrueColor)
        self.connect(self.AlphaBkg, SIGNAL("currentIndexChanged(int)"),
                     self.GetAlphaBkg)
        self.connect(self.PngRead, SIGNAL("currentIndexChanged(int)"),
                     self.GetPngRead)
        self.connect(self.PngKomp, SIGNAL("currentIndexChanged(int)"),
                     self.GetPngKomp)
        self.connect(self.exportoverlay, SIGNAL("clicked()"), 
                     self.makeoverview)
        self.connect(self.placemarks, SIGNAL("currentIndexChanged(int)"),
                     self.GetIcons)
        self.connect(self.refresh, SIGNAL("clicked()"), 
                     self.aggiorna)


    def setLonValue(self, lon):
        #global longi
        #longi = lon
        #return longi
        self.lon = lon
        

    def setLatValue(self, lat):
        #global latit
        #latit = lat
        #return lattit
        self.lat = lat

    def aggiorna(self):
        #self.longitude.setText(longi)
        #self.latitude.setText(latit)
        newlon = str(self.lon)
        newlat = str(self.lat)
        self.longitude.setText(newlon)
        self.latitude.setText(newlat)


    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 GetlegendFile(self, index):
        global legendfile
        legendfile = self.inputrasterlegend.itemText(index)
        return legendfile

    def GetlegendColor(self, index):
        global legendcolor
        legendcolor = self.textlegendcolor.itemText(index)
        return legendcolor

    def GetTrueColor(self, index):
        global TrueColorVal
        TrueColorVal = self.TrueColor.itemText(index)
        return TrueColorVal

    def GetAlphaBkg(self, index):
        global AlphaBkgVal
        AlphaBkgVal = self.AlphaBkg.itemText(index)
        return AlphaBkgVal

    def GetPngRead(self, index):
        global PngReadVal
        PngReadVal = self.PngRead.itemText(index)
        return PngReadVal

    def GetPngKomp(self, index):
        global PngKompVal
        PngKompVal = self.PngKomp.itemText(index)
        return PngKompVal

    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 = '1' , elevation = inputfile , 
                          tiling = tile , output_directory=ExportElev , name=outname)
        if self.Autotiling.isChecked():
            start_command("g.ossim" , elevation=inputfile , 
                          output_directory=ExportElev , name=outname)

    def setkmlbkgcolor(self):
        global kmlbkgcolor
        global kmlbkgcolorName
        kmlbkgcolor = QColorDialog.getColor()
        kmlbkgcolorName = kmlbkgcolor.name()
        if kmlbkgcolor.isValid():
            self.bkgcolor.setStyleSheet("QWidget { background-color: %s }"
                                          % kmlbkgcolor.name() )
            return kmlbkgcolor.name()
        return kmlbkgcolorName

    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 GetIcons(self,index):
        global iconspath
        icons = self.placemarks.itemText(index)
        iconspath = imagepath+str(icons)+str('.png')
        return iconspath


    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]


    def makelegend(self, inputmap, output, lcolor, bkgcolor, flag):
        if self.flag_z.isChecked():
            start_command("d.png.legend", input = inputmap, output_directory = output, 
                       color = lcolor, TRUECOLOR = TrueColorVal, TRANSPARENT = AlphaBkgVal, 
                       PNG_READ = PngReadVal, BACKGROUNDCOLOR = bkgcolor, PNG_COMPRESSION = PngKompVal, 
                       height = self.height.text(), width = self.width.text(), lines = self.AdvLines.text(), 
                       thin = self.AdvThin.text(), labelnum = self.AdvLabelNum.text(), flags = flag)
        else :
            start_command("d.png.legend", input = inputmap, output_directory = output, 
                       color = lcolor, TRUECOLOR = TrueColorVal, TRANSPARENT = AlphaBkgVal, 
                       PNG_READ = PngReadVal, BACKGROUNDCOLOR = bkgcolor, PNG_COMPRESSION = PngKompVal, 
                       height = self.height.text(), width = self.width.text(), lines = self.AdvLines.text(), 
                       thin = self.AdvThin.text(), labelnum = self.AdvLabelNum.text())  

  

    def addoverlay(self, name, outfile):
        kml_overlay = """<ScreenOverlay>
<name>%s</name>
<visibility>0</visibility>
<Icon>
<href>%s</href>
</Icon>
<overlayXY x="0" y="1" xunits="fraction" yunits="fraction"/>
<screenXY x="0" y="1" xunits="fraction" yunits="fraction"/>
<rotationXY x="0" y="0" xunits="fraction" yunits="fraction"/>
<size x="0.5" y="0" xunits="fraction" yunits="fraction"/>
</ScreenOverlay>""" % (name, outfile)
        return kml_overlay
        




    def addplacemark(self, name, icon, names, outimage, lon, lat, alt):
        place = """<name>%s</name>
        <open>1</open>
        <Style id="icon">
            <IconStyle>
                <Icon>
                    <href>%s</href>
                </Icon>
            </IconStyle>
        </Style>
        <Placemark>
            <name>%s</name>
            <visibility>0</visibility>
            <description><![CDATA[<font size="+1"> <a href="http://localhost"><b>Primo link</b></a> </font><br><br> <img height="375" src="%s" width="500"></td><td valign="top"><table width="180" cellspacing="0" cellpadding="0"><tr><td><h2><font size="5"><b>TITOLO</b></font></h2></td></tr><tr><td><p><a href="http://localhost">secondo link</a><br><a href="http://localhost">terzo link</a><br><a href="http://localhost">quarto link</a><br><a href="http://localhost">quinto link </a></p><p></td></tr></table>]]></description>     
        <styleUrl>#icon</styleUrl>
        <Point>
            <altitudeMode>relativeToGround</altitudeMode>
            <coordinates>%s,%s,%s</coordinates>
        </Point>     
    </Placemark>""" % (name, icon, names, outimage, lon, lat, alt)
        return place


    def makeoverview(self):
        name = self.legendname.text()
        #lon = self.longitude.text()
        #lat = self.latitude.text()
        color = legendcolor
        outputfile = QFileDialog.getSaveFileName()
        outputpath = os.path.dirname(str(outputfile))
        raster = self.raster
        rast = len(raster)
        kmlfile = []
        filelist = []
        if AlphaBkgVal == 'FALSE':
            bkgcolor = kmlbkgcolorName
            bkgcolor = str(bkgcolor)
            bkgcolor = bkgcolor.replace('#','')
        else :
            bkgcolor = '000000'
        flags = []
        if self.flag_v.isChecked():
            flags.append('-v')
        if self.flag_c.isChecked():
            flags.append('-c')
        if self.flag_n.isChecked():
            flags.append('-n')
        if self.flag_s.isChecked():
            flags.append('-s')
        if self.flag_f.isChecked():
            flags.append('-f')
        if self.flag_z.isChecked():
            flags.append('-z')
        flags = str(flags)
        flags = flags.replace("['",'')
        flags = flags.replace("']",'')
        flags = flags.replace("', '","")
        flag = flags.replace("-","")
        # print flag
        
        for i in range(rast):
            cell = self.data.item(i, 0)
            if cell.checkState() == 2:
                input = str(cell.text())
                self.makelegend(input, outputpath, color, bkgcolor, flag)
                outfile = outputpath+'/'+input+'.png'
                outimage = outputpath+'/'+'image_'+input+'.png'
                ovl = self.addoverlay(input, outfile)
                if self.placemark.isChecked():
                    placemark = self.addplacemark('Placemarks', iconspath, input, outimage, 0, 0, 0)
                kmlfile.append(ovl)
                kmlfile.append(placemark)
                filelist.append(outfile)
        kmlfile = str(kmlfile)
        kmlfile = kmlfile.replace("['","")
        kmlfile = kmlfile.replace("']","")
        kmlfile = kmlfile.replace("\\n","")
        overview = kmlfile.replace("', '","")
        openoverview = """<?xml version="1.0" encoding="UTF-8"?>
		<kml xmlns="http://www.opengis.net/kml/2.2">
		  <Document>
		<Folder>
		  <name>%s</name>
		  <visibility>0</visibility>""" % (name)
        closeoverview = """</Folder>
		</Document>
		</kml>""" 
        kmlout = outputfile 
        f=open(kmlout, 'w')		
        f.write(openoverview)
        f.write(overview)
        f.write(closeoverview)
        f.close()

        filelist.append(str(kmlout))
        #print filelist       
        #self.compresskml(str(kmlout), filelist)

    def compresskml(self, kmlout, filelist):
        kmz = str(kmlout).split('.')[0]+'.kmz'
        zip = zipfile.ZipFile(str(kmz), 'w')
        for i in filelist:
            zip.write(i)
	    zip.close