# -*- coding: utf-8 -*-
"""
/***************************************************************************
 dai
                                 A QGIS plugin
 DAI
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2022-08-02
        git sha              : $Format:%H$
        copyright            : (C) 2022 by pep and pablob
        email                : pep.j@vielca.com; pablo.b@vielca.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
from qgis.PyQt.QtGui import QIcon, QColor
from qgis.PyQt import QtGui, uic
from qgis.PyQt.QtWidgets import QAction, QMessageBox, QTableWidgetItem, QTableWidget
from qgis.core import QgsRasterLayer, QgsCoordinateTransform, QgsRasterProjector, QgsCoordinateReferenceSystem, QgsRasterBandStats, QgsProject, QgsVectorLayer, QgsFillSymbol,QgsRenderContext, QgsColorRampShader, QgsRasterShader, QgsSingleBandPseudoColorRenderer
from qgis.core import QgsMessageLog
from console import console


# Initialize Qt resources from file resources_rc.py
from .resources_rc import *
# Import the code for the dialog
from .DAI_dialog import daiDialog
import os.path
import warnings
from osgeo import gdal, ogr, osr
import numpy as np
import pandas as pd
import datetime

warnings.filterwarnings("ignore")


class dai:
    TYPE_STYLE_POLYGON  = 1
    TYPE_STYLE_POLYLINE = 2
    
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'dai_{}.qm'.format(locale))

        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)
            QCoreApplication.installTranslator(self.translator)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&DAI')

        # Check if plugin was started the first time in current QGIS session
        # Must be set in initGui() to survive plugin reloads
        self.first_start = None

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        """Get the translation for a string using Qt translation API.

        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('dai', message)


    def add_action(
        self,
        icon_path,
        text,
        callback,
        enabled_flag=True,
        add_to_menu=True,
        add_to_toolbar=True,
        status_tip=None,
        whats_this=None,
        parent=None):
        """Add a toolbar icon to the toolbar.

        :param icon_path: Path to the icon for this action. Can be a resource
            path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
        :type icon_path: str

        :param text: Text that should be shown in menu items for this action.
        :type text: str

        :param callback: Function to be called when the action is triggered.
        :type callback: function

        :param enabled_flag: A flag indicating if the action should be enabled
            by default. Defaults to True.
        :type enabled_flag: bool

        :param add_to_menu: Flag indicating whether the action should also
            be added to the menu. Defaults to True.
        :type add_to_menu: bool

        :param add_to_toolbar: Flag indicating whether the action should also
            be added to the toolbar. Defaults to True.
        :type add_to_toolbar: bool

        :param status_tip: Optional text to show in a popup when mouse pointer
            hovers over the action.
        :type status_tip: str

        :param parent: Parent widget for the new action. Defaults None.
        :type parent: QWidget

        :param whats_this: Optional text to show in the status bar when the
            mouse pointer hovers over the action.

        :returns: The action that was created. Note that the action is also
            added to self.actions list.
        :rtype: QAction
        """

        icon = QIcon(icon_path)
        action = QAction(icon, text, parent)
        action.triggered.connect(callback)
        action.setEnabled(enabled_flag)

        if status_tip is not None:
            action.setStatusTip(status_tip)

        if whats_this is not None:
            action.setWhatsThis(whats_this)

        if add_to_toolbar:
            # Adds plugin icon to Plugins toolbar
            self.iface.addToolBarIcon(action)

        if add_to_menu:
            self.iface.addPluginToMenu(
                self.menu,
                action)

        self.actions.append(action)

        return action

    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = ':/plugins/DAI/icons.png'
        self.add_action(
            icon_path,
            text=self.tr(u'DAI (Daily Aerial Image)'),
            callback=self.run,
            parent=self.iface.mainWindow())

        # will be set False in run()
        self.first_start = True


    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&DAI'),
                action)
            self.iface.removeToolBarIcon(action)


    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = daiDialog()
            date_ini = datetime.datetime.now().strftime("%d-%m-%Y")
            date_end = datetime.datetime.now().strftime("%d-%m-%Y")
            qdate_ini = QtCore.QDate.fromString(date_ini, "dd-MM-yyyy")
            qdate_end = QtCore.QDate.fromString(date_end, "dd-MM-yyyy")

            self.dlg.date_ini.setDate(qdate_ini)
            self.dlg.date_end.setDate(qdate_end)
            
            self.dlg.date_ini.show()
            self.dlg.date_end.show()
            
            
            self.dlg.b_run.clicked.connect(self.dai_func_calc)
            self.dlg.b_close.clicked.connect(self.dai_func_close)

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass

    def dai_func_close(self):    
        self.dlg.close()
        
    def dai_func_calc(self):    
        
        aerial_image_ini = self.dlg.aerial_image_ini.filePath()
        aerial_image_end = self.dlg.aerial_image_end.filePath()
        area_of_interes = self.dlg.area_of_interes.filePath()
        working_folder = self.dlg.working_folder.filePath()
        
        root = QgsProject.instance().layerTreeRoot()
        QgsProject.instance().removeAllMapLayers()
        groups = []
        groups.append(root.findGroup('Input'))
        groups.append(root.findGroup('Output'))
        for group in groups:
            if group is not None:
                for child in group.children():
                    QgsProject.instance().removeMapLayer(child.layerId())
                root.removeChildNode(group)

        group_input_data = root.insertGroup(0, "Input")
        group_output_data = root.insertGroup(1, "Output")
        color = list(np.random.choice(range(256), size=3))
        self.dai_load_vector_map_in_group(area_of_interes, self.TYPE_STYLE_POLYLINE, group_input_data, color)

        self.dai_load_map_raster_in_group( aerial_image_ini, group_input_data)
        self.dai_load_map_raster_in_group( aerial_image_end, group_input_data)
        
        
        dst_crop_ini = os.path.join(working_folder, "aerial_image_ini_crop.tiff")
        driver = gdal.GetDriverByName('GTiff')
        options = gdal.WarpOptions(cutlineDSName=area_of_interes, cropToCutline=True, dstNodata = 0)
        gdal.Warp(srcDSOrSrcDSTab=aerial_image_ini,
                    destNameOrDestDS=dst_crop_ini,
                    options=options) 
        crop_tiff_1 = gdal.Open(dst_crop_ini)

        dst_crop_end = os.path.join(working_folder, "aerial_image_end_crop.tiff")
        options = gdal.WarpOptions(cutlineDSName=area_of_interes, cropToCutline=True, dstNodata = 0)
        gdal.Warp(srcDSOrSrcDSTab=aerial_image_end,
                    destNameOrDestDS=dst_crop_end,
                    options=options) 

        DIM_X = int(crop_tiff_1.RasterXSize)
        DIM_Y = int(crop_tiff_1.RasterYSize)

        dst_crop_resample_ini = os.path.join(working_folder, "aerial_image_ini_crop_resample.tiff")
        options = gdal.WarpOptions(width = DIM_X, height = DIM_Y)
        gdal.Warp(srcDSOrSrcDSTab=dst_crop_ini, 
                    destNameOrDestDS=dst_crop_resample_ini, 
                    options=options)
        
        dst_crop_resample_end = os.path.join(working_folder, "aerial_image_end_crop_resample.tiff")
        options = gdal.WarpOptions(width = DIM_X, height = DIM_Y)
        gdal.Warp(srcDSOrSrcDSTab=dst_crop_end, 
                    destNameOrDestDS=dst_crop_resample_end, 
                    options=options)


        crop_resample_1  = gdal.Open(dst_crop_resample_ini)
        red_crop_resample_1 = crop_resample_1.GetRasterBand(1)
        green_crop_resample_1 = crop_resample_1.GetRasterBand(2)
        blue_crop_resample_1 = crop_resample_1.GetRasterBand(3)

        data_red_crop_resample_1 = red_crop_resample_1.ReadAsArray()
        data_green_crop_resample_1 = green_crop_resample_1.ReadAsArray()
        data_blue_crop_resample_1 = blue_crop_resample_1.ReadAsArray()	

        crop_resample_2  = gdal.Open(dst_crop_resample_end)
        red_crop_resample_2 = crop_resample_2.GetRasterBand(1)
        green_crop_resample_2 = crop_resample_2.GetRasterBand(2)
        blue_crop_resample_2 = crop_resample_2.GetRasterBand(3)

        data_red_crop_resample_2 = red_crop_resample_2.ReadAsArray()
        data_green_crop_resample_2 = green_crop_resample_2.ReadAsArray()
        data_blue_crop_resample_2 = blue_crop_resample_2.ReadAsArray()	

        t1 = self.dlg.date_ini.date().toPyDate()
        t2 = self.dlg.date_end.date().toPyDate()

        interval = pd.date_range(start=t1, end= t2).to_pydatetime().tolist()

        last_day = interval[len(interval)-1]
        diff_total = last_day - interval[0]
        for i in interval:
            if i == interval[0] or i == interval[len(interval)-1]:
                continue
            diff_t1 = i - interval[0]
            diff_t2 = interval[len(interval)-1] - i
            
            
            dst_results = os.path.join(working_folder, '{}_interpolation.tiff'.format(i.strftime('%Y%m%d')))
            dst_ds_interpolation = driver.Create(dst_results, 
                                                DIM_X, 
                                                DIM_Y, 
                                                3, 
                                                gdal.GDT_Byte)
            

            
            red_dst_ds_interpolation = dst_ds_interpolation.GetRasterBand(1)
            green_dst_ds_interpolation = dst_ds_interpolation.GetRasterBand(2)
            blue_dst_ds_interpolation = dst_ds_interpolation.GetRasterBand(3)

            data_red_dst_ds_interpolation = red_dst_ds_interpolation.ReadAsArray()
            data_green_dst_ds_interpolation = green_dst_ds_interpolation.ReadAsArray()
            data_blue_dst_ds_interpolation = blue_dst_ds_interpolation.ReadAsArray()	
            
            
            data_red_dst_ds_interpolation = (diff_t1.days / diff_total.days) * data_red_crop_resample_2 + (diff_t2.days / diff_total.days) * data_red_crop_resample_1    
            data_green_dst_ds_interpolation = (diff_t1.days / diff_total.days) * data_green_crop_resample_2 + (diff_t2.days / diff_total.days) * data_green_crop_resample_1    
            data_blue_dst_ds_interpolation = (diff_t1.days / diff_total.days) * data_blue_crop_resample_2 + (diff_t2.days / diff_total.days) * data_blue_crop_resample_1
            

            
            dst_ds_interpolation.SetGeoTransform(crop_resample_2.GetGeoTransform())     
            dst_ds_interpolation.SetProjection(crop_resample_2.GetProjection())
                        
            dst_ds_interpolation.GetRasterBand(1).ComputeStatistics(0)
            dst_ds_interpolation.GetRasterBand(2).ComputeStatistics(0)
            dst_ds_interpolation.GetRasterBand(3).ComputeStatistics(0)
            
            out_band = dst_ds_interpolation.GetRasterBand(1)
            out_band.WriteArray(data_red_dst_ds_interpolation)
            out_band = dst_ds_interpolation.GetRasterBand(2)
            out_band.WriteArray(data_green_dst_ds_interpolation)
            out_band = dst_ds_interpolation.GetRasterBand(3)
            out_band.WriteArray(data_blue_dst_ds_interpolation)
            
            out_band.FlushCache()    
            del dst_ds_interpolation   
            
            self.dai_load_map_raster_in_group(dst_results, group_output_data)     
            
            

    def dai_load_map_raster_in_group(self,pathRasterMap, group):
        if self.dai_exists(pathRasterMap):
            return True
        returnIsValidRasterMap = False
        pathRasterMap = pathRasterMap.strip()    
    
        if (os.path.exists (pathRasterMap)):    
            baseNameRasterMap   = os.path.basename (pathRasterMap)
            baseNameRasterMap = os.path.splitext(baseNameRasterMap)[0]
            layerRasterMap = QgsRasterLayer(pathRasterMap, baseNameRasterMap)
            QgsProject.instance().addMapLayer(layerRasterMap, False)
            group.addLayer(layerRasterMap)
            returnIsValidRasterMap = layerRasterMap.isValid()
    
    #     return returnIsValidRasterMap 
    

    def dai_exists(self, pathRasterMap):
        baseNameRasterMap   = os.path.basename(pathRasterMap)
        baseNameRasterMap = os.path.splitext(baseNameRasterMap)[0]
        layer_names = [layer.name() for layer in QgsProject.instance().mapLayers().values()]
        if baseNameRasterMap in layer_names:
            return True
        else:
            return False


    def dai_load_vector_map_in_group(self, pathVectorMap, type_style, group, colour = (50,50,250)):
        returnLoadVectorMap = False
        pathVectorMap = pathVectorMap.strip()
        if os.path.exists(pathVectorMap):

            baseNameMapaVector = os.path.basename(pathVectorMap)
            baseNameMapaVector = os.path.splitext(baseNameMapaVector)[0]
            layerVectorMap = QgsVectorLayer(pathVectorMap, baseNameMapaVector, 'ogr')
            QgsProject.instance().addMapLayer(layerVectorMap, False)
            group.addLayer(layerVectorMap)

            if type_style == self.TYPE_STYLE_POLYLINE:

                symbols = layerVectorMap.renderer().symbols(QgsRenderContext())
                symbol = symbols[0]
                symbol.setColor(QtGui.QColor.fromRgb(colour[0],colour[1],colour[2]))


            elif type_style == self.TYPE_STYLE_POLYGON:

                Render = layerVectorMap.renderer()
                mySymbol = QgsFillSymbol.createSimple({'color':'blue', 
                                                          'color_border':'#%02x%02x%02x' % colour,
                                                          'style':'no',
                                                          'style_border':'solid'})

                Render.setSymbol(mySymbol)
                layerVectorMap.triggerRepaint()

            returnLoadVectorMap = layerVectorMap.isValid()
        return returnLoadVectorMap, layerVectorMap
    