from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import *
from qgis.core import *
from qgis.gui import *
from qgis.PyQt.QtWidgets import *
from . import GdalTools_utils

try:
    from qgis.PyQt.QtCore import QString
except ImportError:
    QString = str
from processing.core.Processing import Processing
# from processing.core.ProcessingGdalTools_utils import ProcessingGdalTools_utils
from . import ftools_utils
from osgeo import ogr
from processing import *
from osgeo.gdalconst import GA_ReadOnly
from osgeo import gdal
from processing import ProcessingPlugin
# from processing.outputs import OutputRaster
import sys, os
import numpy
from .Ui_downloadWindow import Ui_downloadWindow
from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry
from qgis.PyQt import QtCore, QtGui
from . import GdalTools_utils as Utils
import sys

SYS_DIR  = "C:/OSGeo4W64/apps"
QGIS_DIR = os.path.join(SYS_DIR, 'qgis')


class downloadWindow(QDialog, Ui_downloadWindow):

    def __init__(self, iface):
        QDialog.__init__(self)
        self.iface = iface
        self.setupUi(self)

        self.selectbutton_roi.clicked.connect(self.fillOutput)
        self.selectButton.clicked.connect(self.install)
        #self.buttonBox.accepted.connect(self.downloadImages)
        self.buttonBox.accepted.connect(self.accept)

    def fillOutput(self):
        settings = QSettings()
        lastDir = settings.value("/fTools/lastRasterDir", ".")
        inDir = QFileDialog.getExistingDirectory(self, self.tr("Select directory to save images"), lastDir)

        if not inDir:
            return

        self.workDir = QDir(inDir)
        self.workDir.setFilter(QDir.Files | QDir.NoSymLinks | QDir.NoDotAndDotDot)

        settings.setValue("/fTools/lastRasterDir", inDir)

        self.outputLayerCombo.addItem(inDir)

    def install(self):
        # install sentinelsat package
        import os
        os.system(os.path.join(QGIS_DIR, "python/plugins/RUSLE/install_sentinelsat.bat"))


    def accept(self):
        self.buttonBox.button(QDialogButtonBox.Ok).setDefault(False)
        import os
        outputfolder = self.outputLayerCombo.currentText()

        #parameters
        user = self.line_user.text()
        password = self.line_pass.text()
        start_date = self.startdate.date()
        dt_str_start = start_date.toString('yyyyMMdd')
        end_date = self.finaldate.date()
        dt_str_end = end_date.toString('yyyyMMdd')
        cloud_value = self.cloud.value()

        #create geojson file from shape
        import subprocess

        # reproject shapefile to wgs84

        command_reproj = 'ogr2ogr -f "ESRI Shapefile" -s_srs EPSG:32629 -t_srs EPSG:4326 C://Artigos//SPIE_2019//NovaZonaEstudo//santiago_wgs84.shp C://Artigos//SPIE_2019//NovaZonaEstudo//santiago.shp'
        #command_reproj = ['ogr2ogr', '-f', "ESRI Shapefile", '-s_srs', 'EPSG:32629' '-t_srs', 'EPSG:4326', 'C://Artigos//SPIE_2019//NovaZonaEstudo//santiago_wgs84.shp', 'C://Artigos//SPIE_2019//NovaZonaEstudo//santiago.shp']
        os.system(command_reproj)
        command = ['ogr2ogr', '-f', 'GeoJSON', 'C://Artigos//SPIE_2019//NovaZonaEstudo//santiago.geojson', 'C://Artigos//SPIE_2019//NovaZonaEstudo//santiago_wgs84.shp']
        subprocess.check_call(command)

        import os
        batch = os.path.join(QGIS_DIR, "python/plugins/RUSLE/download.bat")

        with open(batch, 'w') as f:
            text = ['@ECHO OFF','set OSGEO4W_ROOT=C:\OSGeo4W64','call "%OSGEO4W_ROOT%/bin\o4w_env.bat"','call "%OSGEO4W_ROOT%/bin\qt5_env.bat"','call "%OSGEO4W_ROOT%/bin\py3_env.bat"',
                    'SET PYTHONHOME=%OSGEO4W_ROOT%/apps\Python27','SET PYTHONPATH=%OSGEO4W_ROOT%/apps\Python27\Lib','SET PYTHONPATH=%OSGEO4W_ROOT%/apps\Python36\Lib',
                    'PATH %OSGEO4W_ROOT%/apps\Python27\Scripts;%PATH%']
            text_cmd = 'C:\OSGeo4W64/apps\Python27\Scripts\sentinelsat.exe -u '+str(user) + ' -p ' + str(password) + ' -s ' + str(dt_str_start) + ' -e ' + str(dt_str_end) + ' -cloud ' + str(cloud_value) + ' --uuid 0d7bb0a5-5a0e-4de4-a41e-1599edf26825 --sentinel 2 --path ' + str(outputfolder)+' -d'
            text.append(text_cmd)
            separate = '\n'.join(text)
            #QMessageBox.about(self, "teste", str(separate))
            f.write(separate)
        f.close()


        os.system(os.path.join(QGIS_DIR, "python/plugins/RUSLE/download.bat"))
