# -*- coding: utf-8 -*-
"""
/***************************************************************************
 active_bands_evolution
                                 A QGIS plugin
 oui
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2022-04-06
        git sha              : $Format:%H$
        copyright            : (C) 2022 by oui2
        email                : oui3@mamacita.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QFileDialog
from qgis.core import QgsProject

from qgis.core import QgsProcessing, QgsVectorLayer, Qgis
import processing

# Initialize Qt resources from file resources.py
from .resources import *

# Import the code for the dialog
from .active_channel_evolution_dialog import active_channel_evolution_classDialog
from .valley_bottom_processing import valley_bottom_processing
from .active_channel_evolution_processing import active_channel_processing
from .detect_starting_point import detect_starting_point
import os.path

# Pycharm debug server
# To use it, you need to use a 'python remote debug' configuration into pycharm *pro*
# Then 'pip install pydevd-pycharm~=221.5591.52' # at the time of writing (20022-05-27)

try:
    import pydevd_pycharm
    pydevd_pycharm.settrace('localhost', port=53100, stdoutToServer=True, stderrToServer=True)
    print("Debugging into pycharm")
except:
    print("No remote debug configuration")


class active_channel_evolution:
    """QGIS Plugin Implementation."""

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

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

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

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

        We implement this ourselves since we do not inherit QObject.

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

        :returns: Translated version of message.
        :rtype: QString
        """

        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('active_channel_evolution', 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/diachronix/active_channel_evolution_icon.png'
        self.add_action(
            icon_path,
            text=self.tr('Building of the blocks'),
            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('&Diachronix'), action)
            self.iface.removeToolBarIcon(action)

# some useful functions
    def select_output_blocks_vb(self):
        blocks_vb, _filter = QFileDialog.getSaveFileName(
            self.dlg, self.tr('Select output layer for valley bottom blocks'),
            filter=self.tr('GeoPackage files (*.gpkg);;ESRI Shapefile (*.shp)'))
        self.dlg.lineEditExportValleyFloorBlocks.setText(blocks_vb)

    def select_output_tab_blocks_vb(self):
        tab_blocks_vb, _filter = QFileDialog.getSaveFileName(
            self.dlg, caption=self.tr('Select output table of the valley bottom blocks'),
            filter=self.tr('Comma Separated Values [CSV] (*.csv);;Microsoft Excel files (*.xlsx);;Open Document Spreadsheet (*.ods)'))
        self.dlg.lineEditExportTabValleyFloorBlocks.setText(tab_blocks_vb)

    def select_input_blocks_vb(self):
        input_blocks_vb, _filter = QFileDialog.getOpenFileName(
            self.dlg, caption=self.tr('Select the layer of the valley bottom blocks to use'),
            filter=self.tr('GeoPackage files (*.gpkg);;ESRI Shapefile (*.shp)'))
        self.dlg.lineEditInBlocksValleyFloor.setText(input_blocks_vb)

    def select_output_blocks_ac(self):
        blocks_ac, _filter = QFileDialog.getSaveFileName(
            self.dlg, self.tr('Select output file for the active channel blocks'),
            filter=self.tr('GeoPackage files (*.gpkg);;ESRI Shapefile  (*.shp)'))
        self.dlg.lineEditExportActiveBandBlocks.setText(blocks_ac)

    def select_output_tab_blocks_ac(self):
        tab_blocks_ac, _filter = QFileDialog.getSaveFileName(
            self.dlg, caption=self.tr('Select output table of the active channel blocks'),
            filter=self.tr('Comma Separated Values [CSV] (*.csv);;Microsoft Excel files (*.xlsx);;Open Document Spreadsheet (*.ods)'))
        self.dlg.lineEditExportTabActiveBandBlocks.setText(tab_blocks_ac)

# Starting of the core of the script #
    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 = active_channel_evolution_classDialog()

        # Selecting output paths of table and blocks (default) when button is clicked
        self.dlg.pushButtonExportValleyFloorBlocks.clicked.connect(self.select_output_blocks_vb)
        self.dlg.pushButtonExportTabValleyFloorBlocks.clicked.connect(self.select_output_tab_blocks_vb)
        self.dlg.pushButtonInBlocksValleyFloor.clicked.connect(self.select_input_blocks_vb)
        self.dlg.pushButtonExportTabActiveBandBlocks.clicked.connect(self.select_output_tab_blocks_ac)
        self.dlg.pushButtonExportActiveBandBlocks.clicked.connect(self.select_output_blocks_ac)

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec()

        # we check if we run the processing of the valley bottom
        flag_run_vb = self.dlg.checkBoxRunValleyFloor.isChecked()
        # we check if we run the processing of the active channel
        flag_run_ac = self.dlg.checkBoxRunActiveBand.isChecked()

        # we check if we run both the processings of the valley bottom and of the active channel
        if self.dlg.checkBoxRunBoth.isChecked():
            flag_run_vb = True
            flag_run_ac = True

        # we check if we detect the starting point of the valley bottom layer
        flag_detect_start_point = self.dlg.checkBoxDetectStart.isChecked()

        # we check if we load the temporary layers of the bottom valley processing
        if self.dlg.checkBoxLoadTempLayersValleyFloor.isChecked():
            flag_load_temp_vb = True
        else:
            flag_load_temp_vb = False

        # we check if we load the temporary layers of the active channel processing
        if self.dlg.checkBoxLoadTempLayersActiveBand.isChecked():
            flag_load_temp_ac = True
        else:
            flag_load_temp_ac = False

        # we define the temporary names of the different layers which will be produced
        name_valley_bottom_blocks = self.tr('Valley bottom blocks')
        name_valley_bottom_centerline = self.tr('Valley bottom centerline')
        name_valley_bottom_cross_sections = self.tr('Valley bottom cross-sections')
        name_valley_bottom_rk = self.tr('Valley bottom river kilometers')
        name_active_channel_blocks = self.tr('Active channel blocks')
        name_active_channel_centerline = self.tr('Active channel centerline')
        name_starting_point = self.tr('Starting point')

        # When OK is pressed
        if result:
            try:
                # we grab the value to use for the width of the cross-sections
                cross_section_width = self.dlg.spinBoxWidthTransects.value()
                # we grab the value to use as distance between two transects
                cross_section_distance = self.dlg.spinBoxDistTransects.value()
                # we grab the path where to export the layer containing the blocks of the valley bottom
                export_vb = self.dlg.lineEditExportValleyFloorBlocks.text()
                # we grab the path where to export the csv containing the blocks of the valley bottom
                export_csv_vb = self.dlg.lineEditExportTabValleyFloorBlocks.text()
                # we grab if we have to reverse the centerline of the valley floor
                flag_reverse_vb = self.dlg.checkBoxReverseValleyFloor.isChecked()

                # we grab the layer of the blocks of the valley bottom to use to process the active channel
                input_blocks_vb = self.dlg.lineEditInBlocksValleyFloor.text()
                # we grab the path where to export the layer containing the blocks of the active channel
                export_ac = self.dlg.lineEditExportActiveBandBlocks.text()
                export_csv_ac = self.dlg.lineEditExportTabActiveBandBlocks.text()

                # we grab the layer of the valley bottom
                selected_layer_vb = self.dlg.comboBoxValleyFloor.currentLayer()

                # we grab the layer of the active channel
                selected_layer_ac = self.dlg.comboBoxActiveBand.currentLayer()

                outputs = {}

                # if the user wants to detect the starting point of the valley bottom
                if flag_detect_start_point == True:
                    detect_starting_point(QgsProject, outputs, QgsProcessing, processing, selected_layer_vb,
                                          name_starting_point)

                # if the user wants to run only the processing of the valley bottom
                if (flag_run_vb == True and flag_run_ac == False) and flag_detect_start_point == False:
                    valley_bottom_processing(QgsProject, QgsVectorLayer, outputs, QgsProcessing, processing,
                                             selected_layer_vb, flag_reverse_vb, cross_section_width,
                                             cross_section_distance, export_vb, export_csv_vb, flag_load_temp_vb,
                                             name_valley_bottom_blocks, name_valley_bottom_centerline,
                                             name_valley_bottom_cross_sections, name_valley_bottom_rk)

                # if the user wants to run only the processing of the active channel
                if flag_run_ac == True and flag_run_vb == False:
                    active_channel_processing(QgsProject, QgsVectorLayer, outputs, QgsProcessing, processing,
                                              selected_layer_ac, input_blocks_vb, export_ac, export_csv_ac,
                                              flag_load_temp_ac, name_active_channel_blocks,
                                              name_active_channel_centerline)
                # if the user wants to run in one time the processing of the valley bottom followed by the processing
                # of the active channel
                if flag_run_vb == True and flag_run_ac == True:
                    self.iface.messageBar().pushMessage(self.tr("Step 1 - Valley bottom processing"), level=Qgis.Info)
                    self.iface.mainWindow().repaint()
                    input_blocks_vb = valley_bottom_processing(QgsProject, QgsVectorLayer, outputs, QgsProcessing,
                                                               processing, selected_layer_vb,
                                                               flag_reverse_vb, cross_section_width,
                                                               cross_section_distance, export_vb, export_csv_vb,
                                                               flag_load_temp_vb, name_valley_bottom_blocks,
                                                               name_valley_bottom_centerline,
                                                               name_valley_bottom_cross_sections, name_valley_bottom_rk)
                    self.iface.messageBar().clearWidgets()
                    self.iface.messageBar().pushMessage(self.tr("Step 2 - Active channel processing"), level=Qgis.Info)
                    self.iface.mainWindow().repaint()
                    active_channel_processing(QgsProject, QgsVectorLayer, outputs, QgsProcessing, processing,
                                              selected_layer_ac, input_blocks_vb, export_ac, export_csv_ac,
                                              flag_load_temp_ac, name_active_channel_blocks,
                                              name_active_channel_centerline)

                # Show success message when finished
                self.iface.messageBar().clearWidgets()
                self.iface.messageBar().pushMessage("♪♪ This is the End, my only friend, the End ♪♪",
                                                    level=Qgis.Success, duration=5)

                # we disconnect from the different menus
                self.dlg.pushButtonExportValleyFloorBlocks.clicked.disconnect(self.select_output_blocks_vb)
                self.dlg.pushButtonExportTabValleyFloorBlocks.clicked.disconnect(self.select_output_tab_blocks_vb)
                self.dlg.pushButtonExportActiveBandBlocks.clicked.disconnect(self.select_output_blocks_ac)
                self.dlg.pushButtonExportTabActiveBandBlocks.clicked.disconnect(self.select_output_tab_blocks_ac)
                self.dlg.pushButtonInBlocksValleyFloor.clicked.disconnect(self.select_input_blocks_vb)

            except Exception as inst:
                # print info in console
                print(type(inst))  # the exception instance
                print(inst.args)  # arguments stored in .args
                print(inst)
                # send a message to the user
                self.iface.messageBar().clearWidgets()
                self.iface.mainWindow().repaint()
                self.iface.messageBar().pushMessage(self.tr("Something went wrong. See Python console for details :/"),
                                                    level=Qgis.Critical)
