# -*- coding: utf-8 -*-
"""
/***************************************************************************
 WAPlugin
                                 A QGIS plugin
 Provides access to all the WaPOR data and includes it in the QGIS canvas as another raster layer, providing WaPOR data easy access to the QGIS users. Moreover, the water accounting and productivity component of the plugin will help the water management, providing the opportunity of calculating water accounting indicators, through the creation of maps and reports.
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2020-12-01
        git sha              : $Format:%H$
        copyright            : (C) 2020 by WAP Team
        email                : waplugin.qgis@gmail.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, QDate, QTime, QDateTime, Qt
from qgis.PyQt.QtGui import QIcon 
from qgis.PyQt.QtWidgets import QAction, QApplication, QMessageBox, QTableWidgetItem

from qgis.analysis import QgsRasterCalculatorEntry, QgsRasterCalculator
from qgis.core import QgsRasterLayer, QgsMapLayerProxyModel, QgsCoordinateReferenceSystem

# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the dialog
from .wap_plugin_dialog import WAPluginDialog
from .wap_plugin_data_details import WAPluginDataDetails
from .wap_plugin_loading_window import WAPluginLoadingWindow
import os.path
import os  
from itertools import compress

import tempfile
import json
from shapely.geometry import mapping
from shapely.wkt import loads

from PyQt5.QtCore import pyqtSignal, QRunnable, pyqtSlot, QThreadPool, QObject	

from .utils.wapordl_ext import wapor_map 

try:
    from .utils.managers import Wapor2APIManager, Wapor3APIManager, FileManager, CanvasManager
    from .utils.indicators import IndicatorCalculator, INDICATORS_INFO
    from .utils.tools import CoordinatesSelectorTool

except ModuleNotFoundError as e:
    print('Module [{}] required and not found please install it'.format(e.name))
    QMessageBox.information(None, "Module import error", '''<html><head/><body>
    <p>Module [<b>{}</b>] required and not found please install it. You can find
     some instructions on how to do it with <b>OSGeo4W Shell</b> on our <a href=
     "https://github.com/WAGIS/wap_plugin"><span style=" text-decoration: 
     underline; color: #0000ff;">GitHub Repository</span></a>.
    <br>
    <br>
    Closing the plugin with System Exit . . .</p></body></html>'''.format(e.name))
    quit()


class WorkerSignals(QObject):
    '''
    Defines the signals available from a running worker thread.

    Supported signals are:
    - finished
        Update bar and load rasters workspace
    - error
        Set progress bar to 0 and print error
    - result
        Not implemented
    - progress
        Not implemented
    '''
    finished = pyqtSignal(object)
    result = pyqtSignal(object)
    progress = pyqtSignal(int)
    error = pyqtSignal(object)

class DownloadThread(QRunnable):

    def __init__(self, region, mapset, folder, file_name, period):
        super().__init__()
        self.region = region
        self.mapset = mapset
        self.folder = folder
        self.file_name = file_name
        self.period = period
        self.signals = WorkerSignals()

    def downloadFromWapordl(self, region, mapset, folder, file_name, period):
        return wapor_map(region=region, variable=mapset, folder=folder,
                         file_name=file_name, period=period, seperate_unscale=True)

    @pyqtSlot()
    def run(self):
        try:
            print("Thread run")
            result = self.downloadFromWapordl(self.region, self.mapset, self.folder,
                                            self.file_name, self.period)
            self.signals.finished.emit(self.file_name+' '+self.mapset)
        except Exception as e:
            print(f"An exception occurred: {e}")
            self.signals.error.emit(str(e))

class WAPlugin:
    """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__)

        self.threadpool = QThreadPool()

        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'WAPlugin_{}.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'&WAPlugin')

        # 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

        # Path of the code Directory
        self.cwd = os.path.dirname(os.path.realpath(__file__))
        self.layer_folder_dir = os.path.join(self.cwd, "layers")

        ## Default Values
        # self.waterProductivityVar = "GBWP"
        # self.resolutionVar = "100m"  #"250m" or "100m" , maybe "30m" works for some area
        # self.startSeasonVar = "2015-01"  # "YYYY-DK" (Dekad)
        # self.endSeasonVar = "2015-18"  # "YYYY-DK" (Dekad)
        # self.indicator_index = 0
        # self.indicator = "Equity"

        # # Locations
        # self.locListContinental = ["Algeria","Angola","Benin","Botswana","Burkina Faso","Burundi","Cameroon","Canary Islands"
        #     ,"Cape Verde","Central African Republic","Ceuta","Chad","Comoros","Côte d'Ivoire"
        #     ,"Democratic Republic of the Congo","Djibouti","Egypt","Equatorial Guinea","Eritrea","Ethiopia"
        #     ,"Gabon","Gambia","Ghana","Guinea","Guinea-Bissau","Kenya","Lesotho","Liberia","Libya"
        #     ,"Madagascar","Madeira","Malawi","Mali","Mauritania","Mauritius","Mayotte","Melilla"
        #     ,"Morocco"  ,"Mozambique","Namibia","Niger","Nigeria"  ,"Republic of the Congo"
        #     ,"Réunion","Rwanda","Saint Helena","São Tomé and Príncipe","Senegal","Seychelles"
        #     ,"Sierra Leone","Somalia","South Africa","Sudan","Swaziland","Tanzania","Togo","Tunisia"
        #     ,"Uganda","Western Sahara","Zambia","Zimbabwe"]

        # self.locListNational = ["Benin","Burundi","Egypt","Ghana","Iraq","Jordan","Kenya","Lebanon","Mali","Morocco"
        #     ,"Mozambique","Niger","Palestine","Rwanda","South Sudan","Sudan","Syrian Arab Republic"
        #     ,"Tunisia","Uganda","Yemen"]

        # self.locListSubNational = ["Awash, Ethiopia", "Bekaa, Lebanon", "Busia, Kenya", "Gezira, Sudan", "Koga, Ethiopia",
        #         "Lamego, Mozambique", "Office du Niger, Mali", "Zankalon, Egypt"] 

        self.rasters_path = "layers"

        self.api2_manag = Wapor2APIManager()
        self.api3_manag = Wapor3APIManager()

        self.ws2Initialized = False
        self.ws3Initialized = False

        self.file_manag = FileManager(self.plugin_dir, self.rasters_path)
        self.canv_manag = CanvasManager(self.iface, self.plugin_dir, self.rasters_path)
        
        self.indic_calc = IndicatorCalculator(self.plugin_dir, self.rasters_path)

        self.years_available = list() 

    # 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('WAPlugin', 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/wap_plugin/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Water Accounting and Productivity Plugin'),
            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'&WAPlugin'),
                action)
            self.iface.removeToolBarIcon(action)

    def updateWaporParams(self):
        self.isWapor2 = self.dlg.wapor2radioButton.isChecked()

        box_text = '''<html><head/><body><p>In order to have access to the WaPOR 
             v{} resources, you sould provide the API Token associated to your 
            <a href="{}"><span style=" text-decoration: underline; color:#0000ff
            ;">account</span></a>. In case you do not have one or do not know 
            how to get the API Token, please refer to the instructions in our <a 
            href="{}"><span style=" text-decoration: underline; color:#0000ff;">
            GitHub Repository</span></a>.</p></body></html>'''

        if self.isWapor2:  
            v = 2
            profile_url = 'https://wapor.apps.fao.org/profile'
            instructions_url = r'https://github.com/WAGIS/wap_plugin/wiki/Login-to-database'
        else:
            v = 3
            profile_url = 'https://data.apps.fao.org/gismgr/web/v2'
            instructions_url = r'https://github.com/un-fao/FAO-Water-Applications/blob/10a70cda0e0023258bc9152e43a73b6e8e20b669/WaPOR/FAO%20GISMGR%202.0%20-%20API%20Reference.pdf'

        self.dlg.signinDescriptionLabel.setText(box_text.format(v, profile_url, instructions_url))
        

    def signin(self):
        """
            Calls the sign in function of the API manager and updates the UI
            in response to the result.
        """
        self.dlg.signinStateLabel.setText('Signing into your WaPOR profile . . .')
        if self.isWapor2:  
            connected = self.api2_manag.signin(self.dlg.apiTokenTextBox.text())
        else:
            connected = self.api3_manag.signin(self.dlg.apiTokenTextBox.text())

        if connected:
            self.dlg.signinStateLabel.setText('API Token confirmed, access granted!!!')
            self.dlg.saveTokenButton.setEnabled(True)
            self.dlg.signinButton.setEnabled(False)

            self.dlg.progressBar.setValue(0)
            self.dlg.downloadButton.setEnabled(True)
            self.dlg.progressLabel.setText ('Connected to WaPOR database')
        else:
            self.dlg.signinStateLabel.setText('Access denied, please check the API Token provided or the internet connection . . .')
            self.dlg.progressLabel.setText ('Fail to connect to Wapor Database . . .')

    def saveToken(self):
        """
            Calls the save token function of the file manager and updates the UI.
        """
        self.file_manag.save_token(self.dlg.apiTokenTextBox.text())
        self.dlg.signinStateLabel.setText('Token file saved in memory . . .')

    def loadToken(self):
        """
            Calls the load token function of the file manager, connects the 
            plugin with the WaPOR database and updates the UI in response to the 
            result.
        """
        APIToken = self.file_manag.load_token()

        if APIToken is not None:
            self.dlg.signinStateLabel.setText('Loading Token from memory and signing into your WaPOR profile . . .')
            connected = self.api2_manag.signin(APIToken)

            if connected:
                self.dlg.signinStateLabel.setText('API Token confirmed, access granted!!!')
                self.dlg.signinButton.setEnabled(False)
                self.dlg.loadTokenButton.setEnabled(False)

                self.dlg.progressBar.setValue(0)
                self.dlg.downloadButton.setEnabled(True)
                self.dlg.progressLabel.setText ('Connected to WaPOR database')
            else:
                self.dlg.signinStateLabel.setText('Access denied, please check the API Token file or the internet connection . . .')
                self.dlg.progressLabel.setText ('Fail to connect to Wapor Database . . .')
        else:
            self.dlg.signinStateLabel.setText('No token file found in memory . . .')

    def listWorkspaces(self):
        """
            Calls the pull workspaces function of the APIs manager and updates 
            the UI in response to the result.
        """
        if self.dlg.tabManager.currentIndex() == 1  and not self.ws2Initialized:
            ## Uses the API of the WaPOR v2 to list workspaces
            self.dlg.progressBar.setValue(10)
            self.dlg.progressLabel.setText ('Fetching data categories ...')
            self.loading_dlg.show()
            self.dlg.workspaceComboBox.clear()
            workspaces = self.api2_manag.pull_workspaces()
            self.dlg.workspaceComboBox.addItems(workspaces.values())
            self.dlg.workspaceComboBox.setEnabled(True)

            index = self.dlg.workspaceComboBox.findText('WAPOR-3', QtCore.Qt.MatchFixedString)
            if index >= 0:
                self.dlg.workspaceComboBox.setCurrentIndex(index)
            self.ws2Initialized = True
            self.dlg.progressBar.setValue(100)
            self.loading_dlg.close()
            self.dlg.progressLabel.setText ('Loaded data categories!')
            self.dlg.downloadButton.setEnabled(True)

        elif self.dlg.tabManager.currentIndex() == 2  and not self.ws3Initialized:
            ## Uses the API of the WaPOR v3 to list workspaces
            self.dlg.progressBar.setValue(10)
            self.dlg.progressLabel.setText ('Fetching data categories ...')
            self.loading_dlg.show()
            self.dlg.workspace3ComboBox_2.clear()
            workspaces = self.api3_manag.pull_workspaces()
            self.dlg.workspace3ComboBox_2.addItems(workspaces.values())
            self.dlg.workspace3ComboBox_2.setEnabled(True)

            index = self.dlg.workspace3ComboBox_2.findText('WAPOR-3', QtCore.Qt.MatchFixedString)
            if index >= 0:
                self.dlg.workspace3ComboBox_2.setCurrentIndex(index)
            self.ws3Initialized = True
            self.dlg.progressBar.setValue(100)
            self.loading_dlg.close()
            self.dlg.progressLabel.setText ('Loaded data categories!')
            self.dlg.downloadButton_2.setEnabled(True)

    def listRasterMemory(self):
        """
            Calls the list rasters function of the file manager and updates 
            the UI in response to the result.
        """
        if self.dlg.tabManager.currentIndex() == 1:
            rasterFolder = self.dlg.rasterFolderExplorer.filePath()
            self.tif_files = self.file_manag.list_rasters(rasterFolder)
            self.dlg.rasterMemoryComboBox.clear()
            self.dlg.rasterMemoryComboBox.addItems(self.tif_files.keys())
        elif self.dlg.tabManager.currentIndex() == 2:
            rasterFolder = self.dlg.rasterFolderExplorer_2.filePath()
            self.tif_files = self.file_manag.list_rasters(rasterFolder)
            self.dlg.rasterMemoryComboBox_2.clear()
            self.dlg.rasterMemoryComboBox_2.addItems(self.tif_files.keys())
        elif self.dlg.tabManager.currentIndex() == 3:
            rasterFolder = self.dlg.rasterFolderExplorer_3.filePath()
            self.tif_files = self.file_manag.list_rasters(rasterFolder)
            self.dlg.rasterMemoryComboBox_3.clear()
            self.dlg.rasterMemoryComboBox_3.addItems(self.tif_files.keys())

    def listRasterCalcMemory(self):
        """
            Calls the list rasters function of the file manager to get the rasters
            for the indicator calculator.
        """
        rasterFolderCalc = self.dlg.rasterFolderCalcExplorer.filePath()
        self.tif_calc_files = self.file_manag.list_rasters(rasterFolderCalc)


    def workspaceChange(self):
        """
            Detects changes on the workspace selection, calls the pull cubes
            function of the API manager, filters the result leaving out the 
            clipped cubes and updates the UI in response to the result.
        """
        QApplication.processEvents()
        self.workspace = self.dlg.workspaceComboBox.currentText()
        self.cubes, timeOptions, countryOptions, levelOptions = self.api2_manag.pull_cubes(self.workspace)

        levelOptions.insert(0,'None')
        timeOptions.insert(0,'None')
        countryOptions.insert(0,'None')


        self.dlg.levelFilterComboBox.clear()
        self.dlg.levelFilterComboBox.addItems(levelOptions)
        self.dlg.timeFilterComboBox.clear()
        self.dlg.countryFilterComboBox.clear()
        self.dlg.timeFilterComboBox.addItems(timeOptions)
        self.dlg.countryFilterComboBox.addItems(countryOptions)

    def workspace3Change(self):
        """
            Detects changes on the workspace3 selection, calls the pull mapsets
            function of the API3 manager.
        """
        QApplication.processEvents()
        self.dlg.mapsetComboBox.setEnabled(False)
        self.workspace3 = self.dlg.workspace3ComboBox_2.currentText()
        self.mapsets = self.api3_manag.pull_mapsets(self.workspace3)

        self.dlg.mapsetComboBox.clear()
        self.dlg.mapsetComboBox.addItems(self.mapsets.keys())
        self.dlg.mapsetComboBox.setEnabled(True)

    def mapsetChange(self):
        """
            Detects changes on the mapset selection, calls the pull rasters
            function of the API3 manager.
        """
        try:
            QApplication.processEvents()
            self.mapset = self.mapsets[self.dlg.mapsetComboBox.currentText()]
        except (KeyError) as exception:
            if not self.dlg.cubeComboBox.currentText() == '' and not None: 
                print('Key not found in cubeChange: ', self.dlg.cubeComboBox.currentText())
            pass

    def levelFilterChange(self):
        levelFilterValue = self.dlg.levelFilterComboBox.currentText()
        if levelFilterValue == 'L1' or levelFilterValue == 'L2':
            self.dlg.countryFilterComboBox.setEnabled(False)
            self.dlg.countryFilterComboBox.setCurrentIndex(0)
        else:
            self.dlg.countryFilterComboBox.setEnabled(True)

        self.updateCubesFiltered()

    def updateCubesFiltered(self):
        levelFilterValue = self.dlg.levelFilterComboBox.currentText()
        timeFilterValue = self.dlg.timeFilterComboBox.currentText()
        countryFilterValue = self.dlg.countryFilterComboBox.currentText()
        if not self.first_start and \
        not levelFilterValue  == '' and \
        not timeFilterValue == '' and \
        not countryFilterValue == '':
            if self.dlg.workspaceComboBox.currentText() == 'WAPOR_2':
                if timeFilterValue == 'None' and \
                countryFilterValue == 'None' and \
                levelFilterValue == 'None':
                    filters = ['-', 'clipped', ')'] #Can I remove clipped???
                    mode = 'neg'
                else:
                    filters = {'level':levelFilterValue,
                            'time':timeFilterValue,
                            'country':countryFilterValue}
                    mode = 'pos'
                filteredCubes = self.api2_manag.filter_cubes(self.cubes, filters, mode)
                if not filteredCubes:
                    filteredCubes =['---']
            else:
                filteredCubes = self.cubes

            self.dlg.cubeComboBox.clear()
            self.dlg.cubeComboBox.addItems(filteredCubes)

    def indicatorChange(self):
        """
            Detects changes on the indicator selection and updates the UI in 
            response to the result.
        """
        self.indicator_key = self.dlg.indicatorListComboBox.currentText()
        self.dlg.indicInfoLabel.setWordWrap(True)
        
        """ Update Indicator Info """
        raster_info = [INDICATORS_INFO[self.indicator_key]['info'] + '\n']
        raster_info.extend(['==' * 20 + '\n'])
        raster_info.extend([raster + ': ' + INDICATORS_INFO[self.indicator_key]['rasters'][raster] + '\n'
                    for raster in INDICATORS_INFO[self.indicator_key]['rasters']])
        raster_info.extend(['--' * 20 + '\n'])
        raster_info.extend([factor + ': ' + INDICATORS_INFO[self.indicator_key]['factors'][factor] + '\n'
                            for factor in INDICATORS_INFO[self.indicator_key]['factors']])
        
        """ Raster Files Filtered Update """
        self.listRasterCalcMemory()

        """ Parameters Update """
        if INDICATORS_INFO[self.indicator_key]['params']['PARAM_1'] == '':
            self.dlg.Param1Label.setText('Not Required')
            self.dlg.Param1ComboBox.setEnabled(False)
        else:
            self.dlg.Param1Label.setText(INDICATORS_INFO[self.indicator_key]['params']['PARAM_1']['label'])
            filteredRasterFiles = self.file_manag.filterRasterFiles(self.tif_calc_files, INDICATORS_INFO[self.indicator_key]['params']['PARAM_1']['type'])
            self.dlg.Param1ComboBox.clear()
            self.dlg.Param1ComboBox.addItems(filteredRasterFiles.keys())
            self.dlg.Param1ComboBox.setEnabled(True)

        if INDICATORS_INFO[self.indicator_key]['params']['PARAM_2'] == '':
            self.dlg.Param2Label.setText('Not Required')
            self.dlg.Param2ComboBox.setEnabled(False)
        else:
            self.dlg.Param2Label.setText(INDICATORS_INFO[self.indicator_key]['params']['PARAM_2']['label'])
            filteredRasterFiles = self.file_manag.filterRasterFiles(self.tif_calc_files, INDICATORS_INFO[self.indicator_key]['params']['PARAM_2']['type'])
            self.dlg.Param2ComboBox.clear()
            self.dlg.Param2ComboBox.addItems(filteredRasterFiles.keys())
            self.dlg.Param2ComboBox.setEnabled(True)

        if INDICATORS_INFO[self.indicator_key]['params']['PARAM_3'] == '':
            self.dlg.Param3Label.setText('Not Required')
            self.dlg.Param3TextBox.setEnabled(False)
        else:
            self.dlg.Param3Label.setText(INDICATORS_INFO[self.indicator_key]['params']['PARAM_3'])
            self.dlg.Param3TextBox.setEnabled(True)

        self.dlg.indicInfoLabel.setText(''.join(raster_info))

        if self.indicator_key == 'Equity':
            self.dlg.outputIndicName.setEnabled(False)
        else:
            self.dlg.outputIndicName.setEnabled(True)

    def showDetails(self):
        """
            Open Details window and print data
        """
        self.details_dlg.dataTableWidget.setColumnWidth(0, 200)
        self.details_dlg.dataTableWidget.setColumnWidth(1, 450)
        self.info = self.api2_manag.pull_cube_info(self.workspace, self.cube)

        row = 0
        self.details_dlg.dataTableWidget.setRowCount(len(self.info))
        for info_ele in self.info:
            self.details_dlg.dataTableWidget.setItem(row, 0, QTableWidgetItem(info_ele['type']))
            self.details_dlg.dataTableWidget.setItem(row, 1, QTableWidgetItem(info_ele['details']))
            self.details_dlg.dataTableWidget.resizeRowToContents(row)
            row += 1
        self.details_dlg.show()

    def cubeChange(self):
        """
            Detects changes on the cube selection, calls the pull dimensions and
            measures functions of the API manager and updates the UI in response
            to the result.
        """
        try:
            QApplication.processEvents()
            self.cube = self.cubes[self.dlg.cubeComboBox.currentText()]['id']
            self.dimensions = self.api2_manag.pull_cube_dims(self.workspace,self.cube)
            self.measures = self.api2_manag.pull_cube_meas(self.workspace,self.cube)

            if 'Season' in self.dimensions:
                self.dimensions.pop('Year', None)

            self.dlg.dimensionComboBox.clear()
            self.dlg.dimensionComboBox.addItems(self.dimensions.keys())
            self.dlg.measureComboBox.clear()
            self.dlg.measureComboBox.addItems(self.measures.keys())

            if self.cube:
                self.dlg.outputRasterCubeID.setText('_'+self.cube+'.tif')
            else:
                self.dlg.outputRasterCubeID.setText('---')
                
        except (KeyError) as exception:
            if not self.dlg.cubeComboBox.currentText() == '' and not None: 
                print('Key not found in cubeChange: ', self.dlg.cubeComboBox.currentText())
            pass

    def measureChange(self):
        """
            Detects changes on the measure selection and updates the UI in 
            response to the result.
        """
        try:
            self.measure = self.measures[self.dlg.measureComboBox.currentText()]
        except (KeyError) as exception:
            if not self.dlg.measureComboBox.currentText() == '' and not None: 
                print('Key not found in measureChange: ', self.dlg.measureComboBox.currentText())
            pass

    def memberChange(self):
        """
            Detects changes on the member selection and storages it in memory.
        """
        try:
            self.member = self.members[self.dlg.memberComboBox.currentText()]
        except (KeyError) as exception:
            if not self.dlg.memberComboBox.currentText() == '' and not None: 
                print('Key not found in memberChange: ', self.dlg.memberComboBox.currentText())
            pass
        
    def memberChangeUntil(self):
        """
            Detects changes on the member selection and storages it in memory.
        """
        try:
            self.member_until = self.members[self.dlg.memberComboBoxUntil.currentText()]
        except (KeyError) as exception:
            if not self.dlg.memberComboBoxUntil.currentText() == '' and not None: 
                print('Key not found in memberChangeUntil: ', self.dlg.memberComboBoxUntil.currentText())
            pass

    def getYearsAvailable(self, members_keys):
        """
            Updates the year available in the given members when the dimension 
            selected changes
        """
        years = set([key.split(' ')[0].split('-')[0] for key in members_keys])
        self.years_available = sorted(years)
        
        self.dlg.yearFilterComboBox.clear()
        self.dlg.yearFilterComboBox.addItems(self.years_available)

        self.dlg.yearFilterComboBoxUntil.clear()
        self.dlg.yearFilterComboBoxUntil.addItems(self.years_available)

    def getMonthsAvailable(self):
        """
            Detects changes in the year and filters the months available in the 
            members of the cube for a give time dimensions
        """
        months_available = self._process_months(self.members.keys(),
                                                     self.dlg.yearFilterComboBox.currentText())

        self.dlg.monthFilterComboBox.clear()
        self.dlg.monthFilterComboBox.addItems(months_available)
        self.updateMembersFiltered()

    def getMonthsAvailableUntil(self):
        """
            Detects changes in the year and filters the months available in the 
            members of the cube for a give time dimensions
        """
        months_available = self._process_months(self.members.keys(),
                                                     self.dlg.yearFilterComboBoxUntil.currentText())

        self.dlg.monthFilterComboBoxUntil.clear()
        self.dlg.monthFilterComboBoxUntil.addItems(months_available)
        self.updateMembersFilteredUntil()

    def _process_months(self, members_keys, year):
        months = set()
        for key in members_keys:
            ym = key.split(' ')[0]
            if ym.split('-')[0] == year:
                months.add(ym.split('-')[1])

        return sorted(months)

    def updateMembersFiltered(self):
        """
            Detects changes in the year and month and filters the members of the
            cube
        """
        if any('Season' in member for member in self.members):
            self.dlg.memberComboBox.clear()
            self.dlg.memberComboBox.addItems(self.members.keys())
        else:
            members_available = self._process_members(self.members.keys(),
                                                    self.dlg.yearFilterComboBox.currentText(),
                                                    self.dlg.monthFilterComboBox.currentText())

            self.dlg.memberComboBox.clear()
            self.dlg.memberComboBox.addItems(members_available)

    def updateMembersFilteredUntil(self):
        """
            Detects changes in the year and month and filters the members of the
            cube
        """
        if any('Season' in member for member in self.members):
            self.dlg.memberComboBoxUntil.clear()
            self.dlg.memberComboBoxUntil.addItems(self.members.keys())
        else:
            members_available = self._process_members(self.members.keys(),
                                                    self.dlg.yearFilterComboBoxUntil.currentText(),
                                                    self.dlg.monthFilterComboBoxUntil.currentText())

            self.dlg.memberComboBoxUntil.clear()
            self.dlg.memberComboBoxUntil.addItems(members_available)

    def _process_members(self, members_keys, year, month):
        bool_list = [year in key and '-'+month in key for key in list(members_keys)]

        return sorted(list(compress(members_keys, bool_list)))

    def dimensionChange(self):
        """
            Detects changes on the dimension selection, calls the pull members
            function of the API manager and updates the UI in response to the 
            result.
        """
        try:
            QApplication.processEvents()
            self.dimension = self.dimensions[self.dlg.dimensionComboBox.currentText()]
            self.members = self.api2_manag.pull_cube_dim_membs(self.workspace,  
                                                               self.cube,
                                                               self.dimension)
            members_keys = self.members.keys()

            if self.dlg.timeFilterComboBox.currentText() == 'Dekadal':
                if len(self.years_available) == 0:
                    self.getYearsAvailable(members_keys)
                self.getMonthsAvailable()
                self.getMonthsAvailableUntil()
                self.dlg.yearFilterComboBox.show()
                self.dlg.monthFilterComboBox.show()
                self.dlg.memberComboBox.show()

                self.dlg.yearFilterComboBoxUntil.show()
                self.dlg.monthFilterComboBoxUntil.show()
                self.dlg.memberComboBoxUntil.show()
            elif self.dlg.timeFilterComboBox.currentText() == 'Monthly':
                if len(self.years_available) == 0:
                    self.getYearsAvailable(members_keys)
                self.getMonthsAvailable()
                self.getMonthsAvailableUntil()
                self.dlg.yearFilterComboBox.show()
                self.dlg.monthFilterComboBox.show()
                self.dlg.memberComboBox.hide()

                self.dlg.yearFilterComboBoxUntil.show()
                self.dlg.monthFilterComboBoxUntil.show()
                self.dlg.memberComboBoxUntil.hide()
            elif self.dlg.timeFilterComboBox.currentText() == 'Seasonal':
                self.seas_members = self.api2_manag.pull_cube_dim_membs(self.workspace,
                                                              self.cube,
                                                              'YEAR')
                self.getYearsAvailable(self.seas_members.keys())
                self.dlg.yearFilterComboBox.show()
                self.dlg.monthFilterComboBox.hide()
                self.dlg.memberComboBox.show()

                self.dlg.yearFilterComboBoxUntil.show()
                self.dlg.monthFilterComboBoxUntil.hide()
                self.dlg.memberComboBoxUntil.show()
            else:
                self.dlg.yearFilterComboBox.hide()
                self.dlg.monthFilterComboBox.hide()
                self.dlg.memberComboBox.show()
                
                self.dlg.yearFilterComboBoxUntil.hide()
                self.dlg.monthFilterComboBoxUntil.hide()
                self.dlg.memberComboBoxUntil.show()
                
                self.dlg.memberComboBox.clear()
                self.dlg.memberComboBox.addItems(members_keys)

                self.dlg.memberComboBoxUntil.clear()
                self.dlg.memberComboBoxUntil.addItems(members_keys)
        except (KeyError) as exception:
            if not self.dlg.dimensionComboBox.currentText() == "" and not None: 
                print('Key not found in dimensionChange: ', self.dlg.dimensionComboBox.currentText())
            pass
    
    def cancelCroppedRaster(self):
        self.cancelDownload = True
        self.dlg.progressLabel.setText('Cancelling the download. Unfinished job')

    def downloadCroppedRaster(self):
        """
            Construct the parameters needed to download a cropped raster, the URL
            and calls the query crop raster of the API 2 manager and the download 
            raster function of the file manager, then updates the UI in response
            to the result.
        """
        if self.dlg.timeFilterComboBox.currentText() == 'Seasonal':
            seas_members_keys = list(self.seas_members.keys())
            year_start_ind = seas_members_keys.index(self.dlg.yearFilterComboBox.currentText())
            year_end_ind = seas_members_keys.index(self.dlg.yearFilterComboBoxUntil.currentText())
            years2crop = [self.seas_members[year_ind] for year_ind in seas_members_keys[year_start_ind:year_end_ind+1]]

            member_keys = list(self.members.keys())
            season_start_ind = member_keys.index(self.dlg.memberComboBox.currentText())
            season_end_ind = member_keys.index(self.dlg.memberComboBoxUntil.currentText())

            temp = [(year, sea) for year in years2crop for sea in sorted(self.members.values())]
            dimensions2crop_tuple = temp[season_start_ind:((year_end_ind-year_start_ind)*2+season_end_ind+1)]
            dimensions2crop = [[{"code": 'YEAR', "values": [year]},
                                {"code": 'SEASON', "values": [season]}] for year, season in dimensions2crop_tuple]
        else:
            member_keys = list(self.members.keys())
            time_start_ind = member_keys.index(self.dlg.memberComboBox.currentText())
            time_end_ind = member_keys.index(self.dlg.memberComboBoxUntil.currentText())
            member_time_frame = [self.members[k] for k in member_keys[time_start_ind:time_end_ind+1]]
            dimensions2crop = [[{"code": self.dimension,
                                 "values": [member_frame]}] for member_frame in member_time_frame]

        if len(dimensions2crop) == 0:
            self.dlg.progressBar.setValue(0)
            self.dlg.progressLabel.setText ('Invalid Time Series. Time until < Time from')
            print("Time Series invalid: Time from should be greater than time until")
            return
        
        params = dict()
        params['cube_code'] = self.cube
        params['cube_workspaceCode'] = self.workspace
        params['measures'] = [self.measure]
        if self.dlg.useCanvasCoordRadioButton.isChecked():
            params['coordinates'] = [self.coord_select_tool.getCanvasScopeCoord()]
            params['crs'] = self.getCrs()
        else:
            params['coordinates'] = [self.queryCoordinates]
            params['coordinates'] = [self.coord_select_tool.shape2box(self.dlg.shapeLayerComboBox.currentLayer())]
            params['crs'] = self.dlg.shapeLayerComboBox.currentLayer().crs().authid()

        params['outputFilePrefix'] = self.dlg.outputRasterName.text()
        params['rast_directory'] = self.dlg.downloadFolderExplorer.filePath()

        self.dlg.cancelButton.setEnabled(True)

        for i, dimensions_payload in enumerate(dimensions2crop):
            member_frame = dimensions_payload[0]["values"][0] if len(dimensions_payload) == 1 \
                else dimensions_payload[1]["values"][0] + dimensions_payload[0]["values"][0] 
            
            print(member_frame)
            progress_value = 20 + ((i+1)/len(dimensions2crop))*60
            self.dlg.progressBar.setValue(progress_value)
            self.dlg.progressLabel.setText ('Downloading Raster {}/{}'.format(i+1, len(dimensions2crop)))
                
            params['outputFileName'] = "{}_{}_{}.tif".format(params['outputFilePrefix'],
                                                             params['cube_code'], str(member_frame).split(',')[0].replace("-", "_").replace("[", "_"))
            params['dimensions'] = dimensions_payload

            print(member_frame)
            print(params['outputFileName'])
            
            print("From CANVAS", [self.coord_select_tool.getCanvasScopeCoord()])
            print("From SHAPE", params['coordinates'])

            rast_url = self.api2_manag.query_crop_raster(params, self.dlg.downloadButton)

            if not rast_url == None:
                self.file_manag.download_raster(rast_url, params['rast_directory'])
                
                self.dlg.progressBar.setValue(100)
                self.dlg.progressLabel.setText('Download {}/{} Complete'.format(i+1, len(dimensions2crop)))
                
                self.listRasterMemory()
                self.indicatorChange()
            else:
                self.dlg.progressBar.setValue(0)
                self.dlg.progressLabel.setText('Download {}/{} Complete'.format(i+1, len(dimensions2crop)))

            if self.cancelDownload:
                self.dlg.progressBar.setValue(0)
                self.dlg.progressLabel.setText('Download {}/{} Complete. Cancelled by user'.format(i+1, len(dimensions2crop)))
                break
        
        self.cancelDownload = False
        self.dlg.downloadButton.setEnabled(True)
        self.dlg.cancelButton.setEnabled(False)

    def download3CroppedRaster(self):
        """
            Construct the parameters needed to download a cropped raster, the URL
            and calls the query crop raster of the API 3 manager and the download 
            raster function of the file manager, then updates the UI in response
            to the result.
        """

        init_date = self.dlg.initDateEdit.date().toString("yyyy-MM-dd")
        end_date = self.dlg.endDateEdit.date().toString("yyyy-MM-dd")

        period = [init_date, end_date]

        print(init_date, end_date)

        if self.dlg.useCanvasCoordRadioButton_2.isChecked():

            canvas_coord = self.coord_select_tool.getCanvasScopeCoord()
            bounding_box = [canvas_coord[0][0],
                            canvas_coord[0][1],
                            canvas_coord[1][0],
                            canvas_coord[2][1]]
            
            print(bounding_box)
            
            # Download data
            self.dlg.progressBar.setValue(10)
            self.dlg.progressLabel.setText (f'Downloading Raster {self.mapset}')

            print('Starting thread')
            thread = DownloadThread(bounding_box, self.mapset,
                                    self.dlg.downloadFolderExplorer_2.filePath(),
                                    self.dlg.outputRasterName_2.text(),
                                    period)
            thread.signals.finished.connect(self.thread_complete)
            thread.signals.error.connect(self.thread_complete)
            self.threadpool.start(thread)
            
        else:

            # Create a temporary directory using the tempfile module
            with tempfile.TemporaryDirectory() as temp_dir:
                layer = self.dlg.shapeLayerComboBox_2.currentLayer()

                # Define the path for the output GeoJSON file within the temporary directory
                geojson_path = f"{temp_dir}.geojson"

                # Create a list to store the GeoJSON features
                features = []

                # Loop through the features in the shapefile
                for feature in layer.getFeatures():
                    # Convert the QGIS geometry to a Shapely object
                    shapely_geom = loads(feature.geometry().asWkt())

                    # Convert the Shapely object back to GeoJSON
                    geojson_geom = mapping(shapely_geom)

                    # Add the GeoJSON feature to the list
                    features.append({
                        "type": "Feature",
                        "properties": feature.attributes(),
                        "geometry": geojson_geom
                    })

                # Write the GeoJSON features to a file
                with open(geojson_path, "w") as f:
                    json.dump({"type": "FeatureCollection", "features": features}, f)

                print(geojson_path)

                # Download data
                self.dlg.progressBar.setValue(10)
                self.dlg.progressLabel.setText (f'Downloading Raster {self.mapset} . . .')
               
                print('Starting thread')
                thread = DownloadThread(geojson_path, self.mapset,
                                        self.dlg.downloadFolderExplorer_2.filePath(),
                                        self.dlg.outputRasterName_2.text(),
                                        period)
                thread.signals.finished.connect(self.thread_complete)
                thread.signals.error.connect(self.thread_complete)
                self.threadpool.start(thread)

    def thread_error(self, msg):
        self.dlg.progressBar.setValue(0)
        self.dlg.progressLabel.setText (f'Error: {msg}!')

    def thread_complete(self, msg):
        self.dlg.progressBar.setValue(100)
        self.dlg.progressLabel.setText (f'Downloaded Raster {msg}!')
        self.listRasterMemory()

    def cancelAllProcesses(self):
        self.dlg.progressLabel.setText (f'Cancelling all pending processes: {len(self.processes)}')

        pass
        self.dlg.progressLabel.setText (f'All processes cancelled')
        self.dlg.progressBar.setValue(100)


    def updateRasterFolder(self):
        if self.dlg.tabManager.currentIndex() == 1:
            rasterFolder = self.dlg.rasterFolderExplorer.filePath()
        elif self.dlg.tabManager.currentIndex() == 2:
            rasterFolder = self.dlg.rasterFolderExplorer_2.filePath()
        elif self.dlg.tabManager.currentIndex() == 3:
            rasterFolder = self.dlg.rasterFolderExplorer_3.filePath()
        self.canv_manag.set_rasters_dir(rasterFolder)
        self.listRasterMemory()

        self.dlg.rasterFolderCalcExplorer.setFilePath(rasterFolder)


    def updateRasterFolderCalc(self):
        self.indicatorChange()
        self.indic_calc.setRastersDir(self.dlg.rasterFolderCalcExplorer.filePath())

    def loadRaster(self):
        """
            Calls the add raster function of the canvas manager.
        """
        if self.dlg.tabManager.currentIndex() == 1:
            raster_name = self.dlg.rasterMemoryComboBox.currentText()
        elif self.dlg.tabManager.currentIndex() == 2:
            raster_name = self.dlg.rasterMemoryComboBox_2.currentText()
        elif self.dlg.tabManager.currentIndex() == 3:
            raster_name = self.dlg.rasterMemoryComboBox_3.currentText()
        self.canv_manag.add_rast(raster_name)
        
    def useCanvasCoord(self):
        """
            TODO
        """
        if self.dlg.tabManager.currentIndex() == 1:
            if self.dlg.useCanvasCoordRadioButton.isChecked():
                self.dlg.shapeLayerComboBox.setEnabled(False)
            else:
                self.dlg.shapeLayerComboBox.setEnabled(True)

        elif self.dlg.tabManager.currentIndex() == 2:
            if self.dlg.useCanvasCoordRadioButton_2.isChecked():
                self.dlg.initDateEdit.setEnabled(True)
                self.dlg.endDateEdit.setEnabled(True)
                self.dlg.shapeLayerComboBox_2.setEnabled(False)
            else:
                self.dlg.initDateEdit.setEnabled(True)
                self.dlg.endDateEdit.setEnabled(True)
                self.dlg.shapeLayerComboBox_2.setEnabled(True)
    
    def checkIndicatorRequirements(self):
        """
            Detects changes in the parameters of the indicators and check its 
            requirements and enable the button to calculate them.
        """
        requirementsFlag = False

        param1_name = self.dlg.Param1ComboBox.currentText()
        param2_name = self.dlg.Param2ComboBox.currentText()

        if self.indicator_key == 'Equity' or \
           self.indicator_key == 'Relative Water Deficit':
            requirementsFlag = True if param1_name != '' else False
        if self.indicator_key == 'Beneficial Fraction' or \
             self.indicator_key == 'Adequacy' or \
             self.indicator_key == 'Overall Consumed Ratio' or \
             self.indicator_key == 'Field Application Ratio (efficiency)' or \
             self.indicator_key == 'Depleted Fraction':
            requirementsFlag = True if param1_name != '' and param2_name != '' else False
        
        self.dlg.calculateButton.setEnabled(requirementsFlag)

    def calculateIndicator(self):
        """ 
            Calculates the selected indicator.
        """
        print('Calculating . . . ')
        
        param1_name = self.dlg.Param1ComboBox.currentText()
        param2_name = self.dlg.Param2ComboBox.currentText()

            
        output_name = self.dlg.outputIndicName.text()+".tif"
        
        print(self.indicator_key)
        if self.indicator_key == 'Equity':
            self.indic_calc.equity(raster=param1_name, outLabel=self.dlg.outputIndicValue)
        elif self.indicator_key == 'Beneficial Fraction':
            self.indic_calc.beneficial_fraction(param1_name, param2_name, output_name)
            self.canv_manag.add_rast(output_name)
        elif self.indicator_key == 'Adequacy':
            try:
                param3_name = float(self.dlg.Param3TextBox.text())
            except ValueError:
                print("Param 3 Input is not a float. Using Default value 1.25 instead")
                self.dlg.Param3TextBox.setText('1.25')
                param3_name = 1.25
                
            self.indic_calc.adequacy(param1_name, param2_name, output_name, Kc=param3_name)
            self.canv_manag.add_rast(output_name)
        # elif self.indicator_key == 'Relative Water Deficit':
        #     self.indic_calc.relative_water_deficit(param1_name, output_name)
        #     self.canv_manag.add_rast(output_name)
        elif self.indicator_key == 'Overall Consumed Ratio':
            try:
                param3_name = float(self.dlg.Param3TextBox.text())
            except ValueError:
                self.indic_calc.showErrorMsg("Param 3 Input is not a float. Using Default value 1.25 instead")
                self.dlg.Param3TextBox.setText('1.25')
                param3_name = 1.25
            self.indic_calc.overall_consumed_ratio(param1_name, param2_name, output_name, V_ws=param3_name)
            self.canv_manag.add_rast(output_name)
        elif self.indicator_key == 'Field Application Ratio (efficiency)':
            try:
                param3_name = float(self.dlg.Param3TextBox.text())
            except ValueError:
                self.indic_calc.showErrorMsg("Param 3 Input is not a float. Using Default value 1.25 instead")
                self.dlg.Param3TextBox.setText('1.25')
                param3_name = 1.25
            self.indic_calc.field_application_ratio(param1_name, param2_name, output_name, V_wd=param3_name)
            self.canv_manag.add_rast(output_name)
        elif self.indicator_key == 'Depleted Fraction':
            try:
                param3_name = float(self.dlg.Param3TextBox.text())
            except ValueError:
                self.indic_calc.showErrorMsg("Param 3 Input is not a float. Using Default value 1.25 instead")
                self.dlg.Param3TextBox.setText('1.25')
                param3_name = 1.25
            self.indic_calc.depleted_fraction(param1_name, param2_name, output_name, V_c=param3_name)
            self.canv_manag.add_rast(output_name)
        else:
            raise NotImplementedError("Indicator: '{}' not implemented yet.".format(self.indicator))
    
    def tabChange(self):
        """
            Updates few things when a tab is changed.
        """
        self.listWorkspaces()

        if self.dlg.tabManager.currentIndex() == 3:
            self.indicatorChange()

    def getCrs(self):
        """
            Returns the active CRS reference in Qgis.
        """
        return self.iface.mapCanvas().mapSettings().destinationCrs().authid()
    
    def enableFromShapeFileOption(self):
        """
            Enable option to select a shape file from the available layers
        """
        self.dlg.shapeLayerComboBox_2.setEnabled(True)

    def enableFromCanvasExtent(self):
        """
            Enable option to select a shape file from the available layers
        """
        self.dlg.shapeLayerComboBox_2.setEnabled(False)

    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 = WAPluginDialog()
            self.details_dlg = WAPluginDataDetails()
            self.loading_dlg = WAPluginLoadingWindow()
            self.loading_dlg.setWindowFlags(QtCore.Qt.CustomizeWindowHint)
            
            self.dlg.setFixedSize(self.dlg.size())

            self.prev_tool = self.iface.mapCanvas().mapTool()

            self.dlg.indicatorListComboBox.addItems(INDICATORS_INFO.keys())

            self.coord_select_tool = CoordinatesSelectorTool(self.iface.mapCanvas())

            self.dlg.downloadButton.setEnabled(False)
            self.dlg.cancelButton.setEnabled(False)
            self.dlg.calculateButton.setEnabled(False)

            self.dlg.saveTokenButton.setEnabled(False)
            self.dlg.useCanvasCoordRadioButton.clicked.connect(self.useCanvasCoord)
            self.dlg.useShapeCoordRadioButton.clicked.connect(self.useCanvasCoord)
            self.dlg.useCanvasCoordRadioButton_2.clicked.connect(self.useCanvasCoord)
            self.dlg.useShapeCoordRadioButton_2.clicked.connect(self.useCanvasCoord)

            self.dlg.shapeLayerComboBox.setFilters(QgsMapLayerProxyModel.PolygonLayer)
            self.dlg.shapeLayerComboBox_2.setFilters(QgsMapLayerProxyModel.PolygonLayer)

            self.dlg.wapor2radioButton.clicked.connect(self.updateWaporParams)
            self.dlg.wapor3radioButton.clicked.connect(self.updateWaporParams)

            self.dlg.signinButton.clicked.connect(self.signin)
            self.dlg.saveTokenButton.clicked.connect(self.saveToken)
            self.dlg.loadTokenButton.clicked.connect(self.loadToken)

            self.dlg.rasterFolderExplorer.setFilePath(self.layer_folder_dir)
            self.dlg.rasterFolderExplorer_2.setFilePath(self.layer_folder_dir)
            self.dlg.rasterFolderExplorer_3.setFilePath(self.layer_folder_dir)
            self.dlg.rasterFolderCalcExplorer.setFilePath(self.layer_folder_dir)
            self.dlg.downloadFolderExplorer.setFilePath(self.layer_folder_dir)
            self.dlg.downloadButton.clicked.connect(self.downloadCroppedRaster)
            self.dlg.cancelButton.clicked.connect(self.cancelCroppedRaster)
            self.dlg.cancelButton_2.clicked.connect(self.cancelAllProcesses)
            self.dlg.loadRasterButton.clicked.connect(self.loadRaster)
            self.dlg.loadRasterButton_2.clicked.connect(self.loadRaster)
            self.dlg.loadRasterButton_3.clicked.connect(self.loadRaster)
            self.dlg.RasterRefreshButton.clicked.connect(self.listRasterMemory)
            self.dlg.RasterRefreshButton_2.clicked.connect(self.listRasterMemory)
            self.dlg.RasterRefreshButton_3.clicked.connect(self.listRasterMemory)

            self.dlg.downloadFolderExplorer_2.setFilePath(self.layer_folder_dir)
            self.dlg.downloadButton_2.clicked.connect(self.download3CroppedRaster)

            self.dlg.rasterFolderExplorer.fileChanged.connect(self.updateRasterFolder)
            self.dlg.rasterFolderExplorer_2.fileChanged.connect(self.updateRasterFolder)
            self.dlg.rasterFolderExplorer_3.fileChanged.connect(self.updateRasterFolder)
            self.dlg.rasterFolderCalcExplorer.fileChanged.connect(self.updateRasterFolderCalc)

            self.dlg.workspaceComboBox.currentIndexChanged.connect(self.workspaceChange)
            self.dlg.workspace3ComboBox_2.currentIndexChanged.connect(self.workspace3Change)
            self.dlg.mapsetComboBox.currentIndexChanged.connect(self.mapsetChange)
            self.dlg.cubeComboBox.currentIndexChanged.connect(self.cubeChange)
            self.dlg.detailsLink.clicked.connect(self.showDetails)

            self.dlg.dimensionComboBox.currentIndexChanged.connect(self.dimensionChange)
            self.dlg.memberComboBox.currentIndexChanged.connect(self.memberChange)
            self.dlg.measureComboBox.currentIndexChanged.connect(self.measureChange)

            self.dlg.levelFilterComboBox.currentIndexChanged.connect(self.levelFilterChange)
            self.dlg.timeFilterComboBox.currentIndexChanged.connect(self.updateCubesFiltered)
            self.dlg.countryFilterComboBox.currentIndexChanged.connect(self.updateCubesFiltered)

            self.dlg.yearFilterComboBox.currentIndexChanged.connect(self.getMonthsAvailable)
            self.dlg.monthFilterComboBox.currentIndexChanged.connect(self.updateMembersFiltered)

            self.dlg.yearFilterComboBoxUntil.currentIndexChanged.connect(self.getMonthsAvailableUntil)
            self.dlg.monthFilterComboBoxUntil.currentIndexChanged.connect(self.updateMembersFilteredUntil)
            self.dlg.memberComboBoxUntil.currentIndexChanged.connect(self.memberChangeUntil)

            self.dlg.indicatorListComboBox.currentIndexChanged.connect(self.indicatorChange)
            self.dlg.tabManager.currentChanged.connect(self.tabChange)

            self.dlg.Param1ComboBox.currentIndexChanged.connect(self.checkIndicatorRequirements)
            self.dlg.Param2ComboBox.currentIndexChanged.connect(self.checkIndicatorRequirements)
        
            self.dlg.calculateButton.clicked.connect(self.calculateIndicator)

            self.dlg.useCanvasCoordRadioButton.clicked.connect(self.enableFromCanvasExtent)

            self.updateWaporParams()
            self.indicatorChange()

            self.queryCoordinates = None
            self.queryCrs = None
            self.cancelDownload = False

            new_crs = QgsCoordinateReferenceSystem('EPSG:4326')
            # Set the CRS of the QGIS canvas to the new CRS
            self.iface.mapCanvas().setDestinationCrs(new_crs)


        # 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
        else:
            # Clean up when closing
            self.iface.mapCanvas().setMapTool(self.prev_tool)
            # self.resetTool()
