from __future__ import print_function
from __future__ import absolute_import
from builtins import str
from PyQt5.QtCore import *
#from PyQt4.QtGui import *
#from PyQt4 import QtCore, QtGui
from qgis.core import *
#from qgis.gui import *
#from Ui_RUSLE_runoff import Ui_RUSLE_runoff
from . import GdalTools_utils as Utils
from osgeo import gdal
import os
import osgeo
try:
    from PyQt5.QtCore import QString
except ImportError:
    QString = str
from . import GdalTools_utils as Utils
from . import ftools_utils
from processing.core.Processing import Processing
import numpy

#class RUSLE_runoff:
    
    #def __init__(self, iface):
        #QDialog.__init__(self)
        #self.iface = iface
        #self.setupUi(self)
        
        #QObject.connect(self.selectButton_meteo, SIGNAL("clicked()"),self.fillInputFileEdit)
        #QObject.connect(self.selectMask, SIGNAL("clicked()"),self.fillInputMask)        
        #QObject.connect(self.buttonBox, SIGNAL("accepted()"), self.convert) 
        #QObject.connect(self.selectButton_out, SIGNAL("clicked()"), self.fillOutputFileEdit)
        #QObject.connect(self.inputLayerCombo_meteo, SIGNAL("currentIndexChanged(QString)"), self.fillInputAttrib)
        
        ## connect help
        #QObject.connect(self.buttonBox.button(QtGui.QDialogButtonBox.Help), SIGNAL("clicked()"), self.help)     
        
# HELP
    #def help(self):
        #QMessageBox.about(self, "RUSLE", """<p><b>R factor</b></p> 
        #<p><b>Definition:</b>  </p>
        #<p><b>Method</b></p> 
        #<p>Input file = Meteorological data (points file); Mask file. </p>
        #<p>Parameters = Interpolation method; Field to define the R column OR fields to define Rain10 and Days10 columns; Cell size. </p>
        #<p>Output file = R factor raster file </p>""")          
        

    # INPUT VECTOR FILE
    #def fillInputFileEdit(self):
        #lastUsedFilter = Utils.FileFilter.lastUsedVectorFilter()
        #inputFile, encoding = Utils.FileDialog.getOpenFileName(self, self.tr( "Select the input file" ), Utils.FileFilter.allVectorsFilter(), lastUsedFilter, True)
        #self.lastEncoding = encoding
        #self.loadFields(inputFile)
        #self.inputLayerCombo_meteo.addItem(inputFile)
        #check = QFile(inputFile) 
        
    #def fillInputAttrib(self, inputFile):
        #self.layer = QgsVectorLayer(unicode(self.inputLayerCombo_meteo.currentText()).encode('utf8'), inputFile  , "ogr")
        #self.linedays.clear()
        #self.linerain.clear()
        #changedField = ftools_utils.getFieldList(self.layer)
        #for f in changedField:
            #if f.type() == QVariant.Int or f.type() == QVariant.String or f.type()==QVariant.Double:
                ##self.lineAttrib.addItem(unicode(f.name()))   
                #self.linerain.addItem(unicode(f.name()))
                #self.linedays.addItem(unicode(f.name()))
                #self.lineR.addItem(unicode(f.name()))
                
    #def loadFields(self, vectorFile = QString()):
        #if vectorFile == None:
            #return
        #try:
            #(fields, names) = Utils.getVectorFields(vectorFile)
        #except Exception, e:
            #QErrorMessage(self).showMessage( str(e) )          
        #self.linerain.clearEditText()
        #self.linedays.clearEditText()
        #ncodec = QTextCodec.codecForName(self.lastEncoding)  
      
    ## INPUT MASK SHAPEFILE
    #def fillInputMask(self):
        #lastUsedFilter = Utils.FileFilter.lastUsedVectorFilter()
        #inputFile, encoding = Utils.FileDialog.getOpenFileName(self, self.tr( "Select the input file" ), Utils.FileFilter.allVectorsFilter(), lastUsedFilter, True)
        #self.lastEncoding = encoding
        #self.inputMaskCombo.addItem(inputFile)
        #check = QFile(inputFile)   
     
    # ------------------------------ // ------------------------------------ // ----------------------------
      
    # OUTPUT RASTER FILE
    #def fillOutputFileEdit(self):
        #lastUsedFilter = Utils.FileFilter.lastUsedRasterFilter()
        #outputFile = Utils.FileDialog.getSaveFileName(self, self.tr( "Select the raster file to save the results to" ), Utils.FileFilter.allRastersFilter(), lastUsedFilter )
        #if outputFile==None:
            #return
        #Utils.FileFilter.setLastUsedRasterFilter(lastUsedFilter)
        
        #self.outputFormat = Utils.fillRasterOutputFormat( lastUsedFilter, outputFile )
        #self.inputLayerCombo_out.setText(outputFile) 
          
     # -------------------------------- // --------------------------------- // -------------------------------
     
# POINTS INTERPOLATION
#def convert(self):   
    # fix_print_with_import
    
# fix_print_with_import
print("Hello world")
    
gdal.AllRegister()
# ------------------------ FIRST METHOD -------------------------------------------------
#self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False)
    #inputLayer = self.inputLayerCombo_meteo.currentText()
inputLayer = 'C:/Users/Lia/Desktop/Artigos/Artigo RUSLE/DADOS/meteo_rain_days10_etrs89.shp'
    #inputMask = self.inputMaskCombo.currentText()
inputMask = 'C:/Users/Lia/Desktop/Artigos/Artigo RUSLE/DADOS/montalegre_etrs89.shp'
    # layer information
layer = QgsVectorLayer(str(inputLayer).encode('utf8'), inputLayer , "ogr")  
vectorlayer_vector =  layer.dataProvider()
layer_mask = QgsVectorLayer(str(inputMask).encode('utf8'), inputMask , "ogr")  
vectorlayer_mask =  layer_mask.dataProvider()        
    # mask extent
extent_rect = vectorlayer_mask.extent()
xmin = extent_rect.xMinimum()
xmax = extent_rect.xMaximum()
ymin = extent_rect.yMinimum()
ymax = extent_rect.yMaximum()
extent = str(xmin) + "," + str(xmax) + "," + str(ymin) + "," + str(ymax)
    # cellsize
    #cellSize = int(self.linePix.value())
cellsize = 30
outPath = self.inputLayerCombo_out.text() 
outPath = 'C:/Users/Lia/Desktop/Artigos/Artigo RUSLE/DADOS/out_cover_app.tif'
    # size of atributte table == number of points
count = layer.featureCount()
    
    
    #if self.comboBoxErosivity.currentText()=='R values':
        #R_values = self.lineR.currentText()
        #if self.comboBoxMethod.currentText()=='Kriging':
            #Processing.initialize()
            ## grid directory (qgis2)
            #kriging_interpolation_R = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/kriging_interpolation_R"        
            #Processing.runAlgorithm("saga:ordinarykrigingglobal", None, inputLayer, R_values, True, 0, 1, False, 100, False, 0.0, 10, 1000, 1.0, 0.1, 1.0, 0.5, cellSize, True, extent, kriging_interpolation_R, None)
            #kriging_int_R = kriging_interpolation_R + "." + "tif"
            
            #mask_R = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/mask_R"
            ## clip grid(interpolation) with polygon (mask)
            #Processing.runAlgorithm("saga:clipgridwithpolygon", None, kriging_int_R, inputMask, outPath)
        #if self.comboBoxMethod.currentText()=="Inverse Distance Weighting":
            ## grid directory (qgis2)
            #idw_interpolation_R = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/idw_interpolation_R"        
            #Processing.runAlgorithm("grass:v.surf.idw", None, inputLayer, count, 2.0, R_values, False, extent, cellSize, -1.0, 0.0001, idw_interpolation_R)
            #idw_int_R = idw_interpolation_R + "." + "tif"
            
            #int_mask_R = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/int_mask_R"
            ## clip grid(interpolation) with polygon (mask)
            #Processing.runAlgorithm("saga:clipgridwithpolygon", None, idw_int_R, inputMask, outPath)
        #if self.comboBoxMethod.currentText()=="Cubic spline approximation (SAGA)":
            ## grid directory (qgis2)
            #cubicSpline_interpolation_R = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/cubicSpline_interpolation_R"        
            #Processing.runAlgorithm("saga:cubicsplineapproximation", None, inputLayer, R_values, 0, 3, count, 5, 140.0, extent, cellSize, cubicSpline_interpolation_R)
            #cubicSpline_int_R = cubicSpline_interpolation_R + "." + "tif"
            
            ## clip grid(interpolation) with polygon (mask)
            #Processing.runAlgorithm("saga:clipgridwithpolygon", None, cubicSpline_int_R, inputMask, outPath)
        #if self.comboBoxMethod.currentText()=="Spatial approximation using spline with tension (GRASS)":
            ## grid directory (qgis2)
            #rst_interpolation_R = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/rst_interpolation_R"        
            #Processing.runAlgorithm("grass:v.surf.rst", None, inputLayer, "", None, R_values, 40, 40, 300, 0.001, 2.5, 1, 0, 0, False, False, extent, cellSize, -1, 0.0001, rst_interpolation_R, None, None, None, None, None)
            #rst_int_R = rst_interpolation_R + "." + "tif"
            
            ## clip grid(interpolation) with polygon (mask)
            #Processing.runAlgorithm("saga:clipgridwithpolygon", None, rst_int_R, inputMask, outPath)        

    # if method == loureiro e coutinho (2001)                    
    #if self.comboBoxErosivity.currentText()=='EI30 = 7.05rain(10)-88.92days(10) Loureiro e Coutinho 2001':
rain_10 = 'rains10'
#QMessageBox.about(self,'RUSLE', str(rain_10))
days_10 = 'rains10'
#QMessageBox.about(self,'RUSLE', str(days_10))

        #if self.comboBoxMethod.currentText()=="Kriging":
            ## rain kriging
            #Processing.initialize()
            ## grid directory (qgis2)
            #kriging_interpolation_rain = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/kriging_interpolation_rain"        
            #Processing.runAlgorithm("saga:ordinarykrigingglobal", None, inputLayer, rain_10, True, 0, 1, False, 100, False, 0.0, 10, 1000, 1.0, 0.1, 1.0, 0.5, cellSize, True, extent, kriging_interpolation_rain, None)
            #kriging_int_rain = kriging_interpolation_rain + "." + "tif"
            #mask_rain = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/mask_rain"
            ## clip grid(interpolation) with polygon (mask)
            #Processing.runAlgorithm("saga:clipgridwithpolygon", None, kriging_int_rain, inputMask, mask_rain)
            #int_mask_rain = mask_rain + "." + "tif"    
            ## days kriging
            #kriging_interpolation_days = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/kriging_interpolation_days"        
            #Processing.runAlgorithm("saga:ordinarykrigingglobal", None, inputLayer, days_10, True, 0, 1, False, 100, False, 0.0, 10, 1000, 1.0, 0.1, 1.0, 0.5, cellSize, True, extent, kriging_interpolation_days, None)
            #kriging_int_days = kriging_interpolation_days + "." + "tif"
            #mask_days = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/mask_days"
            ## clip grid(interpolation) with polygon (mask)
            #Processing.runAlgorithm("saga:clipgridwithpolygon", None, kriging_int_days, inputMask, mask_days)
            #int_mask_days = mask_days + "." + "tif"  
            
            ## Loureiro e Coutinho formula EI30
            ##EI30_kriging = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/EI30_kriging"
            #Processing.runAlgorithm("grass:r.mapcalculator", None, int_mask_rain, int_mask_days, None, None, None, None,  "7.05*A - 88.92*B", extent, cellSize, outPath)
            ##EI30_tif = EI30 + "." + "tif"             
            
    #if self.comboBoxMethod.currentText()=="Inverse Distance Weighting":
Processing.initialize()
    # rain idw
    # grid directory (qgis2)
idw_interpolation_rain = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/idw_interpolation_rain"    
    #QMessageBox.about(self,'RUSLE', str(cellSize))
Processing.runAlgorithm("grass:v.surf.idw", None, inputLayer, count, 2.0, rain_10, False, extent, cellSize, -1.0, 0.0001, idw_interpolation_rain)
idw_int_rain = idw_interpolation_rain + "." + "tif"
int_mask_rain = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/int_mask_rain"
    # clip grid(interpolation) with polygon (mask)
Processing.runAlgorithm("saga:clipgridwithpolygon", None, idw_int_rain, inputMask, int_mask_rain)
mask_idw_rain = int_mask_rain + "." + "tif"
    # days idw
idw_interpolation_days = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/idw_interpolation_days"        
Processing.runAlgorithm("grass:v.surf.idw", None, inputLayer, count, 2.0, days_10, False, extent, cellSize, -1.0, 0.0001, idw_interpolation_days)
idw_int_days = idw_interpolation_days + "." + "tif"
int_mask_days = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/int_mask_days"
    # clip grid(interpolation) with polygon (mask)
Processing.runAlgorithm("saga:clipgridwithpolygon", None, idw_int_days, inputMask, int_mask_days)  
mask_idw_days = int_mask_days + "." + "tif"
    
    # Loureiro e Coutinho formula EI30
EI30 = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/EI30"
Processing.runAlgorithm("grass:r.mapcalculator", None, mask_idw_rain, mask_idw_days, None, None, None, None,  "7.05*A - 88.92*B", extent, cellSize, outPath)
EI30_tif = EI30 + "." + "tif"    
    
            
            
 
            #if self.comboBoxMethod.currentText()=="Cubic spline approximation (SAGA)":
                ## cubic spline rain
                ## grid directory (qgis2)
                #cubicSpline_interpolation_rain = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/cubicSpline_interpolation_rain"        
                #Processing.runAlgorithm("saga:cubicsplineapproximation", None, inputLayer, rain_10, 0, 3, count, 5, 140.0, extent, cellSize, cubicSpline_interpolation_rain)
                #cubicSpline_int_rain = cubicSpline_interpolation_rain + "." + "tif"          
                #cubic_mask_rain = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/cubic_mask_rain"
                ## clip grid(interpolation) with polygon (mask)
                #Processing.runAlgorithm("saga:clipgridwithpolygon", None, cubicSpline_int_rain, inputMask, cubic_mask_rain)
                #mask_cubic_rain = cubic_mask_rain + "." + "tif"
                ## days cubic spline
                #cubicSpline_interpolation_days = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/cubicSpline_interpolation_days"        
                #Processing.runAlgorithm("saga:cubicsplineapproximation", None, inputLayer, rain_10, 0, 3, count, 5, 140.0, extent, cellSize, cubicSpline_interpolation_days)
                #cubicSpline_int_days = cubicSpline_interpolation_days + "." + "tif"                
                #cubic_mask_days = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/cubic_mask_days"
                ## clip grid(interpolation) with polygon (mask)
                #Processing.runAlgorithm("saga:clipgridwithpolygon", None, cubicSpline_int_days, inputMask, cubic_mask_days)  
                #mask_cubic_days = cubic_mask_days + "." + "tif"
                
                ## Loureiro e Coutinho formula EI30
                ##EI30 = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/EI30"
                #Processing.runAlgorithm("grass:r.mapcalculator", None, mask_cubic_rain, mask_cubic_days, None, None, None, None,  "7.05*A - 88.92*B", extent, cellSize, outPath)
                ##EI30_tif = EI30 + "." + "tif"                             
              
            #if self.comboBoxMethod.currentText()=="Spatial approximation using spline with tension (GRASS)":
                ## grid directory (qgis2)
                #rst_interpolation_R = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/rst_interpolation_R"        
                #Processing.runAlgorithm("grass:v.surf.rst", None, inputLayer, "", None, R_values, 40, 40, 300, 0.001, 2.5, 1, 0, 0, False, False, extent, cellSize, -1, 0.0001, rst_interpolation_R, None, None, None, None, None)
                #rst_int_R = rst_interpolation_R + "." + "tif"
                
                ## clip grid(interpolation) with polygon (mask)
                #Processing.runAlgorithm("saga:clipgridwithpolygon", None, rst_int_R, inputMask, outPath)
                ##gdalRaster = gdal.Open(str(int_mask_zone_idw))
                ##x = gdalRaster.RasterXSize
                ##y = gdalRaster.RasterYSize
                ##geo = gdalRaster.GetGeoTransform()
                ##band = gdalRaster.GetRasterBand(1)
                ##data = band.ReadAsArray(0,0,x,y)
                ##QMessageBox.about(self,'RUSLE', str(data))
                ## Fourier index
                ## square precipitation
                ##square_prec = numpy.power(data, 2)
                ##QMessageBox.about(self,'RUSLE', str(square_prec))
                ### sum square precipitation
                ##sum_prec_square = numpy.sum(square_prec)
                ##QMessageBox.about(self,'RUSLE', str(sum_prec_square))
                ### sum of precipitation
                ##sum_prec = numpy.sum(data)
                ##QMessageBox.about(self,'RUSLE', str(sum_prec))
                ### divide to obtain the fourier
                ##fourier = numpy.divide(sum_prec_square, sum_prec)
                ##QMessageBox.about(self,'RUSLE', str(fourier))
                ### if precipitation data < 55mm
                ###if data < 55:
                ##part = numpy.power(fourier, 1.847)
                ##R = (0.07397*part)/float(17.2)
                ## Create an output imagedriver
                ##driver = gdal.GetDriverByName( "GTiff" ) 
                ##outData = driver.Create(str(outPath), x,y,1, gdal.GDT_Float32)
                ##outData.GetRasterBand(1).WriteArray(R)
                ##outData.SetGeoTransform(geo)  
                ##outData = None            

        
        
        
        # points interpolation idw
        #if self.comboBoxMethod.currentText()=="Inverse Distance Weighting":
            #Processing.initialize()
            ## grid directory (qgis2)
            #idw_interpolation = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/idw_interpolation_rusle"        
            #Processing.runAlgorithm("grass:v.surf.idw", None, inputLayer, count, 2.0, Elevation, False, extent, cellSize, -1.0, 0.0001, idw_interpolation)
            #idw_int = idw_interpolation + "." + "tif"
            
            #int_mask = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/int_mask_rusle"
            ## clip grid(interpolation) with polygon (mask)
            #Processing.runAlgorithm("saga:clipgridwithpolygon", None, idw_int, inputMask, int_mask)
            #int_mask_zone_idw = int_mask + "." + "tif"  
            
        ## points interpolation kriging
        #if self.comboBoxMethod.currentText()=="Kriging":
            #Processing.initialize()
            ## grid directory (qgis2)
            #kriging_interpolation = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/kriging_interpolation_rusle"        
            #Processing.runAlgorithm("saga:ordinarykrigingglobal", None, inputLayer, Elevation, True, 0, 1, False, 100, False, 0.0, 10, 1000, 1.0, 0.1, 1.0, 0.5, cellSize, True, extent, kriging_interpolation, None)
            #kriging_int = kriging_interpolation + "." + "tif"
            
            #int_mask_kriging = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/int_mask_kriging_rusle"
            ## clip grid(interpolation) with polygon (mask)
            #Processing.runAlgorithm("saga:clipgridwithpolygon", None, kriging_int, inputMask, int_mask_kriging)
            #int_mask_zone_k = int_mask_kriging + "." + "tif"    
        
        ## points interpolation cubic spline approximation
        #if self.comboBoxMethod.currentText()=="Cubic spline approximation (SAGA)":
            #Processing.initialize()
            ## grid directory (qgis2)
            #cubicSpline_interpolation = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/cubicSpline_interpolation_rusle"        
            #Processing.runAlgorithm("saga:cubicsplineapproximation", None, inputLayer, Elevation, 0, 3, count, 5, 140.0, extent, cellSize, cubicSpline_interpolation)
            #cubicSpline_int = cubicSpline_interpolation + "." + "tif"
            
            #int_mask_cubicSpline = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/int_mask_cubicSpline_rusle"
            ## clip grid(interpolation) with polygon (mask)
            #Processing.runAlgorithm("saga:clipgridwithpolygon", None, cubicSpline_int, inputMask, int_mask_cubicSpline)
            #int_mask_zone_csa = int_mask_cubicSpline + "." + "tif"  
        
        ## points interpolation spatial approximation using spline with tension
        #if self.comboBoxMethod.currentText()=="Spatial approximation using spline with tension (GRASS)":
            #Processing.initialize()
            ## grid directory (qgis2)
            #rst_interpolation = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/rst_interpolation_rusle"        
            #Processing.runAlgorithm("grass:v.surf.rst", None, inputLayer, "", None, Elevation, 40, 40, 300, 0.001, 2.5, 1, 0, 0, False, False, extent, cellSize, -1, 0.0001, rst_interpolation, None, None, None, None, None)
            #rst_int = rst_interpolation + "." + "tif"
            
            #int_mask_rst = QFileInfo(QgsApplication.qgisUserDbFilePath()).path() + "/int_mask_rst_rusle"
            ## clip grid(interpolation) with polygon (mask)
            #Processing.runAlgorithm("saga:clipgridwithpolygon", None, rst_int, inputMask, int_mask_rst)
            #int_mask_zone_spline = int_mask_rst + "." + "tif" 


        # add result into canvas
        #file_info = QFileInfo(outPath)
        #if file_info.exists():
            #layer_name = file_info.baseName()
        #else:
            #return False
        #rlayer_new = QgsRasterLayer(outPath, layer_name)
        #if rlayer_new.isValid():
            #QgsMapLayerRegistry.instance().addMapLayer(rlayer_new)
            ##layer = QgsMapCanvasLayer(rlayer_new)
            ##layerList = [layer]
            ##extent = self.iface.canvas.setExtent(rlayer_new.extent())
            ##self.iface.canvas.setLayerSet(layerList)
            ##self.iface.canvas.setVisible(True)         
            #return True
        #else:
            #return False    
        #QMessageBox.information(self, self.tr( "Finished" ), self.tr( "Aquifer media completed." ) )            