#!/usr/bin/env python
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from grass.script.core import *
from vrt_ui import Ui_Form
import os
from OssimPython import *
import socket

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]))
vrt = apppath+str('/vrt/')
history = []

vrtpath = '%s/vrt/' % (apppath)
app = 'VRT'


class VrtG(QWidget, Ui_Form):
    def __init__(self):
        QWidget.__init__(self)
        self.setupUi(self)
        self.raster = self.RasterList()
        rast = len(self.raster)
        numrow = rast
        self.data.setColumnCount(1)
        self.data.setRowCount(numrow)
        self.data.setEditTriggers(QTableWidget.NoEditTriggers)
        vrtfile = self.filelist()
        self.vrtdata.addItems(vrtfile)
        for i in range(rast):
            item = QTableWidgetItem(raster[i])
            item.setTextAlignment(Qt.AlignCenter)
            item.setCheckState(Qt.Unchecked)
            self.data.setItem(i, 0, item)
        self.connect(self.command, SIGNAL("returnPressed(void)"), self.run_command)
        self.connect(self.hist, SIGNAL("currentIndexChanged(int)"), self.readhistocommand)
        self.connect(self.comboBox, SIGNAL("currentIndexChanged(int)"),
                     self.selectaction)
        self.connect(self.vrtdata, SIGNAL("currentIndexChanged(int)"), self.selectfile)
        self.connect(self.toolButton, SIGNAL("clicked()"),self.runexec)
        self.connect(self.sendraster, SIGNAL("clicked()"),self.sendfile)
        self.connect(self.removeraster, SIGNAL("clicked()"),self.removefile)
        self.connect(self.opendir, SIGNAL("clicked()"),self.filemanager)


    def execute(self):
        self.selectaction()

    def selectaction(self,index):
        global app
        app = self.comboBox.itemText(index)
        return app

    def selectfile(self,index):
        global fileselected
        fileselected = self.vrtdata.itemText(index)
        return fileselected


    def runexec(self):
        if app == str('gdalinfo') :
            self.gdalinfogui()
            print 'arriva'
        if app == str('VRT') :
            self.makerastervrt()
        if app == str('img2rr') :
            self.makerasterpreview()
        if app == str('imageinfo') :
            self.ossimimageinfo()
        if app == str('createhisto') :
            self.makerasterhisto()
        if app == str('mosaic') :
            self.gdalinfogui()
        if app == str('r.report') :
            self.makereport()
        if app == str('r.info') :
            self.makeinfo()
        self.updatefilelist()




    def ossimimageinfo(self):
        raster = self.raster
        rast = len(raster)
        rasterinfo = []
        for i in range(rast):
            cell = self.data.item(i, 0)
            if cell.checkState() == 2:
                input = rasterpath+str(cell.text())
                info = OssimImageInfo(input)
                info = str(info)
                title = '<BR><BR>############# %s #############<BR><BR>' % cell.text()
                rasterinfo.append(title) 
                rasterinfo.append(info)
        rasterinfo = str(rasterinfo)
        rasterinfo = rasterinfo.replace('\\n','<BR>')
        rasterinfo = rasterinfo.replace("']",'')
        rasterinfo = rasterinfo.replace("', u'",'')
        rasterinfo = rasterinfo.replace("', '",'') 
        rasterinfo = rasterinfo.replace("[u'",'') 
        self.outimageinfo.setText(rasterinfo)


    def gdalinfogui(self):
        raster = self.raster
        rast = len(raster)
        rasterinfo = []
        for i in range(rast):
            cell = self.data.item(i, 0)
            if cell.checkState() == 2:
                input = rasterpath+str(cell.text())
                info = GdalInfo(input)
                info = str(info)
                title = '<BR><BR>############# %s #############<BR><BR>' % cell.text()
                rasterinfo.append(title) 
                rasterinfo.append(info)
        rasterinfo = str(rasterinfo)
        rasterinfo = rasterinfo.replace('\\n','<BR>')
        rasterinfo = rasterinfo.replace("']",'')
        rasterinfo = rasterinfo.replace("', u'",'')
        rasterinfo = rasterinfo.replace("', '",'') 
        rasterinfo = rasterinfo.replace("[u'",'') 
        self.outimageinfo.setText(rasterinfo)



    def Greport(self,input):
        s = read_command("r.report", map=input)
        s = s.replace('\n','<BR>')
        #a = parse_key_val(s, '\\n')
        #a = a.keys()
        #a.sort()
        #a = str(a)
        #a = a.replace("', '",'<BR>')
        #a = a.replace('{','')
        #a = a.replace('}','')
        #a = '<pre>'+a+'</pre>'
        return s


    def makereport(self):
        raster = self.raster
        rast = len(raster)
        rasterreport = []
        for i in range(rast):
            cell = self.data.item(i, 0)
            if cell.checkState() == 2:
                input = cell.text()
                report = self.Greport(input)
                title = '<BR><BR>############# %s #############<BR><BR>' % cell.text()
                rasterreport.append(title) 
                rasterreport.append(report)
        rasterreport = str(rasterreport)
        rasterreport = rasterreport.replace("[u'",'')
        rasterreport = rasterreport.replace("',",'')
        rasterreport = rasterreport.replace('"]','')
        rasterreport = rasterreport.replace("']",'')
        rasterreport = rasterreport.replace('",','')
        rasterreport = rasterreport.replace("u'",'')
        self.outimageinfo.setText(rasterreport)



    def Ginfo(self,input):
        s = read_command("r.info", map=input)
        s = str(s)
        s = s.replace('\n','<BR>')
        #a = parse_key_val(s, '\\n')
        #a = a.keys()
        #for i in range(len(a)):
        #    k = 10+i # please fix-me ... the order is not well sorted
        #    a[i]=str(k)+str(a[i])
        #a.sort()
        #a = str(a)
        #a = a.replace("', '",'<BR>')
        #a = a.replace('{','')
        #a = a.replace('}','')
        #a = '<pre>'+a+'</pre>'
        return s


    def makeinfo(self):
        raster = self.raster
        rast = len(raster)
        grassinfo = []
        for i in range(rast):
            cell = self.data.item(i, 0)
            if cell.checkState() == 2:
                input = cell.text()
                infograss = self.Ginfo(input)
                title = '<BR><BR>############# %s #############<BR><BR>' % cell.text()
                grassinfo.append(title) 
                grassinfo.append(infograss)
        grassinfo = str(grassinfo)
        grassinfo = grassinfo.replace("[u'",'')
        grassinfo = grassinfo.replace("',",'')
        grassinfo = grassinfo.replace('"]','')
        grassinfo = grassinfo.replace("']",'')
        grassinfo = grassinfo.replace('",','')
        grassinfo = grassinfo.replace("u'",'')
        self.outimageinfo.setText(grassinfo)




    def makerastervrt(self):
        raster = self.raster
        rast = len(raster)
        for i in range(rast):
            cell = self.data.item(i, 0)
            if cell.checkState() == 2:
                input = rasterpath+str(cell.text())
                output = vrt+str(cell.text())+'.vrt'
                s = Gdal_TranslateVrt(input, output)
                self.outimageinfo.setText('created VRT file : \n'+output) 


    def makerasterpreview(self):
        raster = self.raster
        rast = len(raster)
        for i in range(rast):
            cell = self.data.item(i, 0)
            if cell.checkState() == 2:
                input = rasterpath+str(cell.text())
                output = vrt+str(cell.text())+'.vrt'
                outputpreview = vrt+str(cell.text())+'.ovr'
                s = Gdal_TranslateVrt(input, output)
                p = OssimImg2rr(input, outputpreview)
                self.outimageinfo.setText('created Overview file : \n'+outputpreview)

    def makerasterhisto(self):
        raster = self.raster
        rast = len(raster)
        for i in range(rast):
            cell = self.data.item(i, 0)
            if cell.checkState() == 2:
                input = rasterpath+str(cell.text())
                output = vrt+str(cell.text())+'.vrt'
                outputpreview = vrt+str(cell.text())+'.ovr'
                outputphisto = vrt+str(cell.text())+'.his'
                s = Gdal_TranslateVrt(input, output)
                p = OssimImg2rr(input, outputpreview)
                h = OssimCreateHisto(input, outputphisto)
                self.outimageinfo.setText('created Histogram file : \n'+outputphisto)
                

    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 readhistocommand(self,index):
        hcmd = self.hist.itemText(index)
        self.command.setText(hcmd)

    def run_command(self):
        grasshistory =  grassenv['GISDBASE']+'/'+grassenv['LOCATION_NAME']+'/'+ \
		           grassenv['MAPSET']+'/.bash_history'
        cmd = str(self.command.text())
        history.append(cmd)
        grasshist = open(grasshistory,"r")
        hlines = grasshist.readlines()
        for i in hlines:
            history.append(i)
        thinhist = {}.fromkeys(history)
        thistory = thinhist.keys()
        thistory.sort()
        self.hist.addItems(thistory)
        stdouterr = os.popen4(cmd)[1].read()
        self.outimageinfo.append(stdouterr)


    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 updatefilelist(self):
        vrtdata = self.filelist()
        self.vrtdata.clear()
        self.vrtdata.addItems(vrtdata)

    def filelist(self):
        vrtdata = []
        for filename in os.listdir(vrt):
            if '.vrt' in filename:
                vrtdata.append(filename)
        vrtdata.sort()
        return vrtdata

    def sendfile(self):
        filepath = vrt+fileselected
        ossim = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ossim.connect(("127.0.0.1", 8000))
        ossimxml = "<Add target=':idolbridge'><Image groupType='groundTexture'><filename>%s</filename> <id>%s</id><name>%s</name></Image></Add>" % (filepath,filepath,fileselected)
        ossim.send(ossimxml)
        ossim.close()
        self.outimageinfo.setText('Added VRT file to OssimPlanetQt : \n'+filepath) 
        print ossimxml

    def removefile(self):
        filepath = vrt+fileselected
        ossim = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        ossim.connect(("127.0.0.1", 8000))
        ossimxml = "<Remove target=':idolbridge' id='%s' />" % (filepath)
        ossim.send(ossimxml)
        ossim.close()
        self.outimageinfo.setText('Removed VRT file from OssimPlanetQt : \n'+filepath) 
        print ossimxml
