# -*- coding: utf-8 -*-
"""
/***************************************************************************
 QGISFGIPlugin
                                 A QGIS plugin
 This plugin is for classifying samples of pastures areas.
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2022-06-20
        git sha              : $Format:%H$
        copyright            : (C) 2022 by Tharles de Sousa Andrade | LAPIG - UFG
        email                : irtharles@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.                                   *
 *                                                                         *
 ***************************************************************************/
"""
import gc
import os
import json
import time
from datetime import datetime
from os.path import expanduser, exists
from functools import partial

import requests as req
from qgis.core import (
    Qgis,
    QgsFillSymbol,
    QgsProject,
    QgsRasterLayer,
    QgsVectorLayer,
    QgsField,
    QgsFields,
    QgsFeature,
    QgsProject,
    QgsGeometry,
    QgsVectorDataProvider,
    QgsVectorFileWriter
)
from qgis.PyQt.QtCore import QCoreApplication, QSettings, Qt, QTranslator, QEvent, QObject, QVariant
from qgis.PyQt.QtGui import QIcon, QPixmap
from qgis.PyQt.QtWidgets import (
    QAbstractScrollArea,
    QAction,
    QApplication,
    QFileDialog,
    QMessageBox,
    QScrollArea,
    QVBoxLayout,
    QPlainTextEdit,
    QProgressBar,
    QHBoxLayout,
    QLabel,
    QWidget,
    QPushButton
)
from qgis import utils
from .qgis_fgi_plugin_dockwidget import QGISFGIPluginDockWidget

# Initialize Qt resources from file resources.py
from .resources import *
from .sources import connections
from .src.inspections import InspectionController
from .src.models.config_db import init_db, reset_config, set_config, get_config
from .src.ui.date_time_edit import NoScrollOrArrowKeyFilter

class QGISFGIPlugin(QObject):
    """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
        """
        try:
            super(QGISFGIPlugin, self).__init__()
            # 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',
                'QGISFGIPlugin_{}.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('&QGIS Fast Grid Inspection')
            # TODO: We are going to let the user set this up in a future iteration
            self.toolbar = self.iface.addToolBar('QGISFGIPlugin')
            self.toolbar.setObjectName('QGISFGIPlugin')

            # print "** INITIALIZING QGISFGIPlugin"
            self.plugin_is_active = False
            self.dock_widget = None
            self.scroll_area = None
            self.tiles_layer = None
            self.work_dir = None
            self.canvas = None
            self.root = None
            self.group = None
            self.tiles = None
            self.type_inspection = None
            self.current_tile_index = 0
            self.selected_class_bing = None
            self.selected_class_google = None
            self.current_pixels_layer = None
            self.inspection_controller = None
            self.campaigns_config = None
            self.layer_bing = None
            self.layer_google = None
            self.config = init_db()
            self.scroll = None
            self.show_imports_buttons = None
            self.load_config_from = 'local'
            self.layers_plugin = []
            self.reset_button = None
            self.reload_button = None
            self.progress_message_bar = None
            self.progress_bar = None

        except Exception as e:
            print("Error during initialization:", str(e))

    # 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('QGISFGIPlugin', 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:
            self.toolbar.addAction(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 = os.path.join(os.path.dirname(__file__), 'icon.png')
        self.add_action(
            icon_path,
            text=self.tr('Fast Grid Inspection'),
            callback=self.run,
            parent=self.iface.mainWindow(),
        )
        self.reload_button = QPushButton("")
        self.reload_button.setToolTip("Click here to reload the plugin QGIS Fast Grid")
        reload_icon_path = os.path.join(os.path.dirname(__file__), 'img', 'reload.png')
        reload_icon = QIcon(reload_icon_path)
        self.reload_button.setIcon(reload_icon)
        self.reload_button.clicked.connect(self.reload_plugin)
        self.toolbar.addWidget(self.reload_button)

    # --------------------------------------------------------------------------

    def onClosePlugin(self):
        if hasattr(self, 'dock_widget'):
            if hasattr(self.dock_widget, 'localConfig'):
                self.dock_widget.localConfig.removeEventFilter(self)
        self.reset_plugin_instance(reset=False)
        # disconnects
        if hasattr(self, 'dock_widget'):
            if hasattr(self.dock_widget, 'closingPlugin'):
                self.dock_widget.closingPlugin.disconnect(self.onClosePlugin)
        self.reset_button = None
        self.reload_button = None

        if hasattr(self, 'toolbar') and self.toolbar:
            # Remove the actions from the toolbar
            self.toolbar.removeAction(self.reset_button)
            self.toolbar.removeAction(self.reload_button)

        self.remove_datasource()
        self.dock_widget = None
        self.plugin_is_active = False
        QgsProject.instance().removeMapLayers(self.list_layers())
        QApplication.instance().setOverrideCursor(Qt.ArrowCursor)
        gc.collect()

    def remove_path(self, path):
        def safe_remove(_path, retries=8, delay=1):
            for _ in range(retries):
                try:
                    os.remove(_path)
                    break
                except PermissionError:
                    time.sleep(delay)

        if os.path.exists(path):
            safe_remove(path)

    def remove_files_with_extension(self, directory, extension):
        self.start_processing()
        directory = os.path.dirname(__file__) + directory
        total_files = len([name for name in os.listdir(directory)])
        processed_files = 0
        for filename in os.listdir(directory):
            self.update_progress(10)
            if 'default_tiles.gpkg' not in filename:
                if filename.endswith(extension):
                    file_path = os.path.join(directory, filename)
                    self.remove_path(file_path)

            processed_files += 1
            progress = (processed_files / total_files) * 100
            self.update_progress(progress)
        self.finish_progress()

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""

        # print "** UNLOAD QGISFGIPlugin"
        for action in self.actions:
            self.iface.removePluginMenu(self.tr('&Fast Grid Inspection'), action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    # --------------------------------------------------------------------------
    @staticmethod
    def is_valid_json(text):
        try:
            json.loads(text)
            return True
        except json.JSONDecodeError:
            return False

    def eventFilter(self, obj, event):
        if hasattr(self, 'dock_widget') and self.dock_widget is not None:
            if obj == self.dock_widget.localConfig and event.type() == QEvent.FocusOut:
                content = self.dock_widget.localConfig.toPlainText()
                color = '#e6fff2'
                if not self.is_valid_json(content):
                    color = "#ffcccc"
                    self.iface.messageBar().pushMessage(
                        'LOCAL CONFIG',
                        'The provided configuration has syntax errors for the JSON format, please correct them.',
                        level=Qgis.Critical,
                        duration=10,
                    )

                self.dock_widget.localConfig.setStyleSheet("QPlainTextEdit { background-color:" + color + "; }")
                return True  # event was handled

        return super(QGISFGIPlugin, self).eventFilter(obj, event)

    def open_google_satellite(self):

        url = 'https://mt1.google.com/vt/lyrs=s&x=%7Bx%7D&y=%7By%7D&z=%7Bz%7D'
        service_url = url.replace('=', '%3D').replace('&', '%26')
        qgis_tms_uri = 'type=xyz&zmin={0}&zmax={1}&url={2}'.format(
            0, 19, service_url
        )

        layer = QgsRasterLayer(qgis_tms_uri, 'Google', 'wms')
        self.layer_google = layer
        self.add_layer(layer.id())
        if layer.isValid():
            QgsProject.instance().addMapLayer(layer)
            QgsProject.instance().layerTreeRoot().findLayer(
                layer.id()
            ).setItemVisibilityChecked(False)
        else:
            print('Layer failed to load!')

    def add_layer(self, layer_id: str):
        """Add a layer ID to the list if it's not already present."""
        if layer_id not in self.layers_plugin:
            self.layers_plugin.append(layer_id)

    def remove_layer(self, layer_id: str):
        """Remove a layer ID from the list if it exists."""
        if layer_id in self.layers_plugin:
            self.layers_plugin.remove(layer_id)

    def list_layers(self):
        """Return the list of layer IDs."""
        return self.layers_plugin

    def open_bing_satellite(self):

        url = 'http://ecn.t3.tiles.virtualearth.net/tiles/a{q}.jpeg?g=1'

        qgis_tms_uri = 'type=xyz&zmin={0}&zmax={1}&url={2}'.format(0, 19, url)

        layer = QgsRasterLayer(qgis_tms_uri, 'Bing', 'wms')
        self.layer_bing = layer
        self.add_layer(layer.id())
        if layer.isValid():
            QgsProject.instance().addMapLayer(layer)
            QgsProject.instance().layerTreeRoot().findLayer(
                layer.id()
            ).setItemVisibilityChecked(True)
        else:
            print('Layer failed to load!')

    # def get_config(self, key):
    #     """Load config file and get value of key"""
    #     if key is 'inspectionConfig':
    #         return self.config.get_inspection_config()
    #
    #     return getattr(self.config, key)
    #
    def get_config(self, key):
        """Load config file and get value of key"""
        return get_config(key)

    def set_config(self, key, value):
        """Write config in config file"""
        set_config(key, value)

    # def set_config(self, key, value):
    #     """Write config in config file"""
    #     with db.atomic() as transaction:  # Start a new transaction
    #         try:
    #             setattr(self.config, key, value)
    #             # if key is 'inspectionConfig':
    #             # print('inspectionConfig', value)
    #             self.config.save()
    #         except Exception as e:
    #             logger.exception(e)
    #             print(f"Error setting config for key: {key}, value: {value}. Error: {e}")
    #             transaction.rollback()  # Rollback the transaction if there's an error
    def clear_config(self):
        self.config = reset_config()

    def handle_remote_url(self, config):
        if "cell_size" not in config:
            config['cell_size'] = 10

        for _class in config['classes']:
            if "rgba" not in _class:
                _class['rgba'] = _class['rgb']
        return config

    def load_type_inspections(self):
        """Load campaigns from service: https://ows.lapig.iesa.ufg.br/api/global-pasture/campaigns"""
        if self.load_config_from == 'url':
            url = self.dock_widget.configURL.text()
            if url is not None:
                resp = req.get(
                    url
                )

                # self.campaigns_config = self.handle_remote_url(resp.json()[0])
                self.campaigns_config = resp.json()[0]
                self.set_config(key='configURL', value=url)
                self.update_progress(30)
            else:
                self.iface.messageBar().pushMessage(
                    'ERROR',
                    'It was not possible to load the settings from the provided URL.',
                    level=Qgis.Critical,
                    duration=5,
                )
        else:
            self.update_progress(30)
            local_config = json.loads(self.dock_widget.localConfig.toPlainText())
            self.campaigns_config = local_config
            self.set_config(key='inspectionConfig', value=self.campaigns_config)

        self.show_config_url(False)
        self.show_local_config(False)
        self.enable_config_buttons(False)

    def config_tiles(self):
        self.current_pixels_layer = None
        self.update_progress(30)
        try:
            tile = self.tiles[self.current_tile_index]
            self.dock_widget.tileInfoBing.setText(
                f'Tile {self.current_tile_index + 1} of {len(self.tiles)}'
            )
            self.dock_widget.tileInfoGoogle.setText(
                f'Tile {self.current_tile_index + 1} of {len(self.tiles)}'
            )
            self.update_progress(50)
            self.inspection_controller.create_grid_pixels(tile)
            self.update_progress(90)
            self.dock_widget.lblSearch.setVisible(True)
            self.dock_widget.spinSearch.setVisible(True)
            self.dock_widget.btnSearch.setVisible(True)
            self.dock_widget.btnNewInspection.setVisible(True)
            self.dock_widget.zoom.setVisible(True)
            self.dock_widget.btnSkip.setVisible(True)
            self.dock_widget.spinSearch.setMaximum(999999999)
            self.update_progress(100)
            self.finish_progress()
        except Exception as e:
            self.iface.messageBar().pushMessage(
                'CONFIG_TILES',
                str(e),
                level=Qgis.Critical,
                duration=5,
            )
            self.finish_progress()
            print(e)

    def load_tiles(self):
        QApplication.instance().setOverrideCursor(Qt.BusyCursor)
        """Load tiles from layer"""
        instance = QgsProject.instance()
        open_layers = [layer for layer in instance.mapLayers().values()]
        for layer in open_layers:
            if layer.name() == 'tiles':
                self.tiles = [f.attributes() for f in layer.getFeatures()]
        QApplication.instance().setOverrideCursor(Qt.ArrowCursor)

    def find_first_valid_date(self, layer, date_field):
        for feature in layer.getFeatures():
            date_value = feature[date_field]
            if date_value and date_value != '2000-01-01':
                return date_value
        return '2000-01-01'
    def create_and_populate_tiles_review_layer(self, files):
        # Create an empty memory layer with the required fields
        fields = QgsFields()
        fields.append(QgsField('fid', QVariant.Int))
        fields.append(QgsField("name_file", QVariant.String))
        fields.append(QgsField("path", QVariant.String))
        fields.append(QgsField("bing_start", QVariant.String))
        fields.append(QgsField("bing_end", QVariant.String))
        fields.append(QgsField("google_start", QVariant.String))
        fields.append(QgsField("google_end", QVariant.String))

        tiles_review = QgsVectorLayer("Polygon?crs=EPSG:3857", "tiles_review", "memory")

        provider = tiles_review.dataProvider()
        provider.addAttributes(fields)
        tiles_review.updateFields()

        # For each file, load it, extract data and add a new feature with those attributes to the memory layer
        for file_path in files:
            layer = QgsVectorLayer(file_path, os.path.basename(file_path), "ogr")
            if not layer.isValid():
                print(f"Layer failed to load: {file_path}")
                continue
            bing_image_start_date = self.find_first_valid_date(layer, 'bing_image_start_date')
            bing_image_end_date = self.find_first_valid_date(layer, 'bing_image_end_date')
            google_image_start_date = self.find_first_valid_date(layer, 'google_image_start_date')
            google_image_end_date = self.find_first_valid_date(layer, 'google_image_end_date')

            # Add a feature with these attributes to the memory layer
            fid = int(os.path.basename(file_path).split('_')[0])

            new_feature = QgsFeature()
            new_feature.setFields(tiles_review.fields())
            new_feature.setGeometry(QgsGeometry.fromRect(layer.extent()))
            new_feature['fid'] = fid
            new_feature['name_file'] = os.path.basename(file_path)
            new_feature['path'] = file_path
            new_feature['bing_start'] = bing_image_start_date
            new_feature['bing_end'] = bing_image_end_date
            new_feature['google_start'] = google_image_start_date
            new_feature['google_end'] = google_image_end_date

            provider.addFeature(new_feature)

        work_dir = os.path.expanduser("~")
        output_file_path = f"{work_dir}/tiles_review_{datetime.now().strftime('%Y-%m-%d').replace('-', '_')}.gpkg"

        writer = QgsVectorFileWriter.writeAsVectorFormat(
            tiles_review,
            output_file_path,
            "utf-8",
            tiles_review.crs(),
            "GPKG"
        )

        if writer[0] == QgsVectorFileWriter.NoError:
            print(f"Successfully saved to {output_file_path}")
        else:
            print("Failed to save:", writer[1])

        return output_file_path

    def create_tiles_file_from_dir(self):
        directory = QFileDialog.getExistingDirectory(
            self.dock_widget,
            'Choose the directory with the files containing the tiles',
            expanduser('~'),
            QFileDialog.ShowDirsOnly,
        )

        # If user doesn't select any directory, just return an empty list
        if not directory:
            return []

        # Get all files in the directory
        files = [os.path.join(directory, f) for f in os.listdir(directory) if
                 os.path.isfile(os.path.join(directory, f))]
        return self.create_and_populate_tiles_review_layer(files)

    def open_tiles_file(self, from_config=False):
        QApplication.instance().setOverrideCursor(Qt.BusyCursor)

        """Open Tiles file Dialog"""
        selected_mode = self.dock_widget.comboMode.currentText()

        interpreter_name = self.dock_widget.interpreterName.text()

        if interpreter_name != '':
            self.set_config(
                key='interpreterName', value=interpreter_name.upper()
            )

        if from_config:
            layer_path = self.get_config('filePath')
            self.dock_widget.tabWidget.setCurrentIndex(1)
            self.current_tile_index = self.get_config('currentTileIndex')
        else:
            if selected_mode == 'INSPECT':
                layer_path = str(
                    QFileDialog.getOpenFileName(
                        caption='Choose the file with the tiles',
                        filter='Geopackage (*gpkg)',
                    )[0]
                )
            else:
                layer_path = self.create_tiles_file_from_dir()

        if layer_path != '' and exists(layer_path):
            self.tiles_layer = QgsVectorLayer(layer_path, 'tiles', 'ogr')
            symbol = QgsFillSymbol.createSimple(
                {
                    'color': '0,0,0,0',
                    'color_border': 'red',
                    'width_border': '0.7'
                }
            )
            fill_layer = symbol.symbolLayer(0)
            fill_layer.setStrokeStyle(Qt.DashLine)
            self.tiles_layer.renderer().setSymbol(symbol)
            self.dock_widget.fieldFileName.setText(layer_path)
            QgsProject.instance().addMapLayer(self.tiles_layer)
            self.add_layer(self.tiles_layer.id())
            self.iface.setActiveLayer(self.tiles_layer)
            self.iface.zoomToActiveLayer()
            self.load_tiles()
            self.set_config(key='filePath', value=layer_path)

            if from_config:
                self.config_tiles()

            QApplication.instance().setOverrideCursor(Qt.ArrowCursor)
            return True
        else:
            self.iface.messageBar().pushMessage(
                'ERROR READ FILE',
                'Tiles GPKG not found',
                level=Qgis.Critical,
                duration=5,
            )
            QApplication.instance().setOverrideCursor(Qt.ArrowCursor)
            return False

    def get_dir_path(self, from_config=False):
        if from_config:
            directory = self.get_config('workingDirectory')
        else:
            directory = QFileDialog.getExistingDirectory(
                self.dock_widget,
                'Select Directory',
                expanduser('~'),
                QFileDialog.ShowDirsOnly,
            )
            self.dock_widget.btnInitInspections.setVisible(True)

        self.dock_widget.fieldWorkingDirectory.setText(directory)
        self.set_config(key='workingDirectory', value=directory)

    def load_classes(self):
        image_date = self.dock_widget.imageDate.date()

        if not self.inspection_controller.date_is_valid(
                image_date.toString('yyyy-MM-dd')
        ):
            image_date = None

        if not image_date:
            msg = QMessageBox()
            msg.setIcon(QMessageBox.Question)
            msg.setText('The image date is required to classify this tile!')
            msg.setInformativeText(
                'If the image date was not found, the tile would be ignored. Do you confirm the missing date of the image?'
            )
            msg.setWindowTitle('INSPECTION TILES')
            msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            retval = msg.exec_()
            if retval == 16384:
                self.inspection_controller.init_inspection_tile(
                    no_image_date=True
                )
        else:
            if self.get_config('imageSource') == 'BING':
                self.dock_widget.labelClassBing.setVisible(True)
                self.dock_widget.selectedClassBing.setVisible(True)
            else:
                self.dock_widget.btnNext.setVisible(True)
                if self.dock_widget.btnShowYes.isChecked():
                    self.dock_widget.importBingClassification.setVisible(True)
                self.dock_widget.labelClassGoogle.setVisible(True)
                self.dock_widget.selectedClassGoogle.setVisible(True)

            self.inspection_controller.init_inspection_tile()

    def init_inspections(self):
        self.start_processing()
        self.update_progress(10)
        interpreter_name = self.dock_widget.interpreterName.text()
        if interpreter_name != '':
            QApplication.instance().setOverrideCursor(Qt.BusyCursor)

            self.load_type_inspections()
            self.config_tiles()
            self.set_config(
                key='interpreterName', value=interpreter_name.upper()
            )
            self.dock_widget.btnInitInspections.setVisible(False)

            if self.get_config('imageSource') == 'BING':
                self.dock_widget.tabWidget.setTabEnabled(1, True)
                self.dock_widget.tabWidget.setCurrentIndex(1)

            else:
                self.dock_widget.tabWidget.setTabEnabled(2, True)
                self.dock_widget.tabWidget.setCurrentIndex(2)

        else:
            self.iface.messageBar().pushMessage(
                '',
                f'The name of interpreter is required!',
                level=Qgis.Critical,
                duration=5,
            )

    def show_local_config(self, show=False):
        sh = not show
        self.dock_widget.localConfig.setReadOnly(sh)
        color = "#e6e6e6"
        if not sh:
            color = '#fafafa'
        self.dock_widget.localConfig.setStyleSheet("QPlainTextEdit { background-color:" + color + "; }")

    def show_config_url(self, show=False):
        self.dock_widget.configURL.setEnabled(show)

    def enable_config_buttons(self, enable=False):
        self.dock_widget.btnConfigLocal.setEnabled(enable)
        self.dock_widget.btnConfigURL.setEnabled(enable)
        self.dock_widget.btnShowYes.setEnabled(enable)
        self.dock_widget.btnShowNo.setEnabled(enable)
        self.dock_widget.comboMode.setEnabled(enable)

    def on_config_buttons_toggled(self, button):
        actions = {
            'Yes': lambda: setattr(self, 'show_imports_buttons', True),
            'No': lambda: setattr(self, 'show_imports_buttons', False),
            'Local': lambda: setattr(self, 'load_config_from', 'local'),
            'URL': lambda: setattr(self, 'load_config_from', 'url')
        }

        action = actions.get(button)

        if action:
            action()

        if self.show_imports_buttons:
            self.set_config(key='showImportsButtons', value=self.show_imports_buttons)

        if self.load_config_from:
            self.set_config(key='loadConfigFrom', value=self.load_config_from)

        if self.load_config_from == 'local':
            self.show_local_config(True)
        else:
            self.show_local_config(False)

        if self.load_config_from == 'url':
            self.show_config_url(True)
        else:
            self.show_config_url(False)

    def reset_content(self):
        self.plugin_actions(connect=False)
        self.dock_widget.btnFile.setEnabled(True)
        self.dock_widget.btnWorkingDirectory.setEnabled(True)
        self.dock_widget.interpreterName.setEnabled(True)
        self.dock_widget.tabWidget.setCurrentIndex(0)
        self.clear_config()
        self.plugin_actions(connect=True)
        self.dock_widget.spinSearch.setMaximum(999999999)

    def continue_inspecting(self):
        self.start_processing()

        self.get_dir_path(from_config=True)

        if not self.open_tiles_file(from_config=True):
            return

        self.load_config_from = self.get_config('loadConfigFrom')
        self.load_campaign_conf()

        self.show_imports_buttons = self.get_config('showImportsButtons')
        self.dock_widget.interpreterName.setText(
            self.get_config('interpreterName').upper()
        )

        if self.show_imports_buttons:
            self.dock_widget.btnShowNo.setChecked(False)
            self.dock_widget.btnShowYes.setChecked(True)
        else:
            self.dock_widget.btnShowNo.setChecked(True)
            self.dock_widget.btnShowYes.setChecked(False)
        self.start_processing()
        self.update_progress(10)
        self.load_type_inspections()

        self.dock_widget.tabWidget.setTabEnabled(1, True)
        self.dock_widget.tabWidget.setTabEnabled(2, True)

        self.set_config(key='imageSource', value='BING')
        self.update_progress(30)
        self.inspection_controller.on_change_tab(1)
        self.show_config_url(False)
        self.show_local_config(False)
        self.enable_config_buttons(False)
        self.dock_widget.interpreterName.setEnabled(False)
        self.dock_widget.btnFile.setEnabled(False)
        self.dock_widget.btnWorkingDirectory.setEnabled(False)
        self.dock_widget.btnInitInspections.setVisible(False)
        self.update_progress(60)
        self.plugin_actions()
        self.update_progress(100)
        self.finish_progress()

    def zoom_to_tile_layer(self):
        self.iface.setActiveLayer(self.current_pixels_layer)
        self.iface.zoomToActiveLayer()

    def plugin_actions(self, connect=True):
        # Define all connections in a list of tuples
        connections = [
            (self.dock_widget.btnFile.clicked, self.open_tiles_file),
            (self.dock_widget.btnWorkingDirectory.clicked, self.get_dir_path),
            (self.dock_widget.btnClearSelectionBing.clicked, self.inspection_controller.remove_selection),
            (self.dock_widget.btnClearSelectionGoogle.clicked, self.inspection_controller.remove_selection),
            (self.dock_widget.btnInitInspections.clicked, self.init_inspections),
            (self.dock_widget.btnLoadClasses.clicked, self.load_classes),
            (self.dock_widget.btnFinishBing.clicked, self.inspection_controller.start_inspection_google),
            (self.dock_widget.tabWidget.currentChanged, self.inspection_controller.on_change_tab),
            (self.dock_widget.sameImage.clicked, self.inspection_controller.set_same_image),
            (self.dock_widget.importBingClassification.clicked, self.inspection_controller.import_classes_bing),
            (self.dock_widget.btnConfigLocal.clicked, partial(self.on_config_buttons_toggled, 'Local')),
            (self.dock_widget.btnConfigURL.clicked, partial(self.on_config_buttons_toggled, 'URL')),
            (self.dock_widget.btnShowYes.clicked, partial(self.on_config_buttons_toggled, 'Yes')),
            (self.dock_widget.btnShowNo.clicked, partial(self.on_config_buttons_toggled, 'No')),
            (self.dock_widget.btnNewInspection.clicked, self.new_inspection),
            (self.dock_widget.zoom.clicked, self.zoom_to_tile_layer),
            (self.dock_widget.btnSkip.clicked, self.inspection_controller.skip_tile),
            (self.dock_widget.comboMode.currentIndexChanged, self.on_mode_change)
        ]

        # If connecting
        if connect:
            for signal, slot in connections:
                signal.connect(slot)
        # If disconnecting
        else:
            for signal, slot in connections:
                try:
                    signal.disconnect(slot)
                except TypeError as e:

                    pass

    def reset_screen(self):
        self.dock_widget.btnInitInspections.setVisible(False)
        self.dock_widget.btnClearSelectionBing.setVisible(False)
        self.dock_widget.btnClearSelectionGoogle.setVisible(False)
        self.dock_widget.btnLoadClasses.setVisible(False)
        self.dock_widget.tabWidget.setTabEnabled(1, False)
        self.dock_widget.tabWidget.setTabEnabled(2, False)
        self.dock_widget.tabWidget.setTabEnabled(3, False)
        self.dock_widget.labelClassBing.setVisible(False)
        self.dock_widget.labelClassGoogle.setVisible(False)
        self.dock_widget.selectedClassBing.setVisible(False)
        self.dock_widget.selectedClassGoogle.setVisible(False)
        self.dock_widget.classesBing.setVisible(False)
        self.dock_widget.classesGoogle.setVisible(False)
        self.dock_widget.importBingClassification.setVisible(False)
        self.dock_widget.btnFinishBing.setVisible(False)
        self.dock_widget.bingStartDate.setEnabled(False)
        self.dock_widget.btnNext.setVisible(False)
        self.dock_widget.btnNext.setEnabled(False)
        self.dock_widget.bingEndDate.setEnabled(False)
        self.dock_widget.imageDate.setMaximumDateTime(datetime.now())
        self.dock_widget.lblSearch.setVisible(False)
        self.dock_widget.spinSearch.setVisible(False)
        self.dock_widget.btnSearch.setVisible(False)
        self.dock_widget.btnNewInspection.setVisible(False)
        self.dock_widget.zoom.setVisible(False)
        self.dock_widget.btnSkip.setVisible(False)
        self.show_config_url(False)
        self.dock_widget.btnConfigLocal.setChecked(True)
        self.dock_widget.btnShowNo.setChecked(True)
        self.dock_widget.comboMode.setEnabled(True)

        self.dock_widget.btnNext.setToolTip("Generate GPKG of the inspected and classified tile.")
        self.dock_widget.spinSearch.setToolTip("Type the FID that you want to search.")
        self.dock_widget.btnSearch.setToolTip("Run search of tile by FID")
        self.dock_widget.btnNewInspection.setToolTip("Create new Inspection")
        self.dock_widget.zoom.setToolTip("Zoom in on the current layer of tiles being inspected.")
        self.dock_widget.btnSkip.setToolTip("Skip the current tile.")

    def remove_datasource(self):
        for extension in ['.gpkg-shm', '.gpkg-wal', 'gpkg']:
            self.remove_files_with_extension('/datasource', extension)

    def reset_plugin_instance(self, reset=True):
        if reset:
            QgsProject.instance().clear()
            self.iface.mainWindow().statusBar().hide()

        if hasattr(self, 'dock_widget'):
            if hasattr(self.dock_widget, 'fieldFileName'):
                self.dock_widget.fieldFileName.setText('')
            if hasattr(self.dock_widget, 'interpreterName'):
                self.dock_widget.interpreterName.setText('')
            if hasattr(self.dock_widget, 'fieldWorkingDirectory'):
                self.dock_widget.fieldWorkingDirectory.setText('')
            if hasattr(self.dock_widget, 'imageDate'):
                self.dock_widget.imageDate.clear()

        self.iface.actionPan().trigger()
        self.remove_datasource()

    def new_inspection(self):
        msg = QMessageBox()
        msg.setIcon(QMessageBox.Question)
        msg.setText('Do you want to start a new inspection?')
        msg.setWindowTitle('INSPECTION TILES')
        msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        QApplication.instance().setOverrideCursor(Qt.ArrowCursor)
        retval = msg.exec_()
        # 65536 -> No | 16384 -> Yes
        if retval == 16384:
            self.reset_content()
            self.reset_screen()
            self.reset_plugin_instance()
            self.open_google_satellite()
            self.open_bing_satellite()
            self.enable_config_buttons(enable=True)
            self.show_local_config(show=True)
            self.iface.actionZoomToSelected().trigger()
            self.current_tile_index = 0
            self.current_pixels_layer = None

    def load_campaign_conf(self):
        if self.load_config_from == 'local':
            self.dock_widget.btnConfigLocal.setChecked(True)
            self.dock_widget.btnConfigURL.setChecked(False)

            inspection_config = self.get_config('inspectionConfig')
            self.campaigns_config = inspection_config

            self.dock_widget.localConfig.setPlainText(
                json.dumps(inspection_config, indent=4)
            )
        else:
            self.dock_widget.btnConfigLocal.setChecked(False)
            self.dock_widget.btnConfigURL.setChecked(True)
            self.dock_widget.configURL.setText(
                self.get_config('configURL')
            )

    def start_processing(self):
        # Remove existing progress bar if any
        if self.progress_message_bar:
            self.finish_progress()

        self.progress_message_bar = self.iface.messageBar().createMessage("")

        self.progress_bar = QProgressBar()
        self.progress_bar.setMaximum(100)

        # Create a QWidget to hold the progress bar
        container = QWidget()
        layout = QHBoxLayout(container)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(QLabel("Processing..."))
        layout.addWidget(self.progress_bar)
        container.setLayout(layout)

        self.progress_message_bar.layout().addWidget(container)

        self.iface.messageBar().pushWidget(self.progress_message_bar, Qgis.Info)

    def update_progress(self, value):
        if self.progress_bar:
            self.progress_bar.setValue(value)
        else:
            self.start_processing()
            self.progress_bar.setValue(value)

    def finish_progress(self):
        if self.progress_message_bar:
            # Hide and remove the progress bar
            self.iface.messageBar().clearWidgets()
            self.progress_bar = None
            self.progress_message_bar = None

    def reload_plugin(self):
        # Assuming the name of your plugin is 'my_plugin_name'
        name = 'qgis-fgi-plugin'

        # Find the plugin
        plugin = utils.plugins.get(name)
        if plugin is None:
            raise ValueError(f"Plugin {name} not found.")

        # Unload the plugin
        utils.unloadPlugin(name)

        # Load the plugin again
        utils.loadPlugin(name)
        self.onClosePlugin()
        utils.startPlugin(name)

    def reset_configuration(self):
        self.reset_content()
        self.reset_screen()
        self.reset_plugin_instance()
        self.open_google_satellite()
        self.open_bing_satellite()
        self.enable_config_buttons(enable=True)
        self.show_local_config(show=True)

    def config_combo_mode(self):
        items = ["INSPECT", "REVIEW"]
        for item in items:
            self.dock_widget.comboMode.addItem(item)

        self.dock_widget.comboMode.setCurrentText(self.get_config('mode'))

    def on_mode_change(self):
        selected_mode = self.dock_widget.comboMode.currentText()
        self.set_config('mode', selected_mode)

        if selected_mode == 'INSPECT':
            self.dock_widget.labelFile.setText('Tiles file (*.gpkg)')
            self.dock_widget.btnSkip.setText('Skip')
        else:
            self.dock_widget.labelFile.setText('Select the directory with review tile files (*.gpkg)')
            self.dock_widget.btnSkip.setText('Next')

    def run(self):
        """Run method that loads and starts the plugin"""
        if not self.plugin_is_active:
            # print "** STARTING QGISFGIPlugin"

            # dock_widget may not exist if:
            #    first run of plugin
            #    removed on close (see self.onClosePlugin method)
            if self.dock_widget is None:
                # Create the dock_widget (after translation) and keep reference
                self.dock_widget = QGISFGIPluginDockWidget()

            self.dock_widget.btnPointDate.setIcon(
                QIcon(os.path.dirname(__file__) + '/img/copy-point.png')
            )
            self.dock_widget.btnClearSelectionBing.setIcon(
                QIcon(os.path.dirname(__file__) + '/img/delete.png')
            )
            self.dock_widget.btnClearSelectionGoogle.setIcon(
                QIcon(os.path.dirname(__file__) + '/img/delete.png')
            )
            self.dock_widget.logo.setPixmap(
                QPixmap(os.path.dirname(__file__) + '/img/logo-plugin.png')
            )
            self.dock_widget.btnNext.setIcon(
                QIcon(os.path.dirname(__file__) + '/img/save.png')
            )
            self.iface.actionPan().trigger()

            # Feed QGIS with default TMSs.
            connections.xyz(self)
            self.inspection_controller = InspectionController(self)

            self.work_dir = (
                    str.split(__file__, 'qgis_fgi_plugin.py')[0] + 'datasource'
            )
            self.plugin_is_active = True
            self.canvas = self.iface.mapCanvas()
            self.config_combo_mode()
            self.open_google_satellite()
            self.open_bing_satellite()

            self.reset_screen()

            self.dock_widget.setAllowedAreas(Qt.AllDockWidgetAreas)

            self.show_config_url(False)
            self.dock_widget.btnConfigLocal.setChecked(True)
            self.dock_widget.btnShowNo.setChecked(True)
            self.dock_widget.localConfig.installEventFilter(self)

            self.dock_widget.imageDate.installEventFilter(NoScrollOrArrowKeyFilter())

            file = self.get_config('filePath')

            self.campaigns_config = self.get_config('inspectionConfig')

            self.dock_widget.localConfig.setPlainText(
                json.dumps(self.campaigns_config, indent=4)
            )

            if file != '':
                self.continue_inspecting()
            else:
                self.reset_content()

            selected_mode = self.get_config('mode')

            if selected_mode == 'INSPECT':
                self.dock_widget.btnSkip.setText('Skip')
            else:
                self.dock_widget.btnSkip.setText('Next')

            self.iface.actionZoomToSelected().trigger()
            self.dock_widget.closingPlugin.connect(self.onClosePlugin)

            # add scroll
            scroll_tab = QScrollArea()
            scroll_tab.setSizeAdjustPolicy(
                QAbstractScrollArea.AdjustToContents
            )
            self.dock_widget.tabWidget.setMinimumHeight(750)
            scroll_tab.setWidget(self.dock_widget.tabWidget)

            self.dock_widget.gridMain.addWidget(scroll_tab)

            # show the dock_widget
            self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dock_widget)


            self.dock_widget.show()
