# -*- coding: utf-8 -*-
"""
/***************************************************************************
 QMydro
                                 A QGIS plugin
 This is the QGIS interface for calling QMydro catchment delineation and characterization
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-12-30
        git sha              : $Format:%H$
        copyright            : (C) 2025 by Callan Schonrock, HydroRepo
        email                : callansch@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, Qt, QRunnable, QThreadPool, pyqtSignal, QObject, pyqtSlot, QVariant
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction
from qgis.core import QgsMapLayerProxyModel, QgsRasterLayer, QgsVectorLayer, QgsProject, QgsFeature, QgsGeometry, QgsPoint, QgsField, QgsFields, QgsWkbTypes, Qgis, edit, QgsVectorFileWriter, QgsCoordinateTransformContext
# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the DockWidget
from .qmydro_dockwidget import QMydroDockWidget
import os.path

# QMydro Dependent
import subprocess
from .scripts import convertToRORB, convertToWBNM, convertToURBS
import shutil


class SubprocessSignals(QObject):
    finished = pyqtSignal()

class SubprocessWorker(QRunnable):
    def __init__(self, batch_file, plugin_directory):
        super().__init__()
        self.batch_file = batch_file
        self.plugin_directory = plugin_directory
        self.signals = SubprocessSignals()

    @pyqtSlot()
    def run(self):
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags &= ~subprocess.STARTF_USESHOWWINDOW  # Prevent the window from being minimized
        subprocess_proc = subprocess.Popen(self.batch_file, cwd=os.path.join(self.plugin_directory, "scripts"), startupinfo=startupinfo)
        subprocess_proc.wait()
        self.signals.finished.emit()

class QMydro:
    """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',
            'QMydro_{}.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'&QMydro')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'QMydro')
        self.toolbar.setObjectName(u'QMydro')

        #print "** INITIALIZING QMydro"

        self.pluginIsActive = False
        self.dockwidget = 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('QMydro', 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 = ':/plugins/qmydro/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u''),
            callback=self.run,
            parent=self.iface.mainWindow())

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

    def onClosePlugin(self):
        """Cleanup necessary items here when plugin dockwidget is closed"""

        #print "** CLOSING QMydro"

        # disconnects
        self.dockwidget.closingPlugin.disconnect(self.onClosePlugin)

        # remove this statement if dockwidget is to remain
        # for reuse if plugin is reopened
        # Commented next statement since it causes QGIS crashe
        # when closing the docked window:
        # self.dockwidget = None

        self.pluginIsActive = False


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

        #print "** UNLOAD QMydro"

        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&QMydro'),
                action)
            self.iface.removeToolBarIcon(action)
        # remove the toolbar
        del self.toolbar

    #--------------------------------------------------------------------------
    
    def toggleBreakup(self, state):
        if state == 2:
            self.dockwidget.subcatSize.setEnabled(True)
            self.dockwidget.subcatSizeLabel.setEnabled(True)
        else:
            self.dockwidget.subcatSize.setEnabled(False)
            self.dockwidget.subcatSizeLabel.setEnabled(False)
    
    def UpdateRecalcRequirements(self, text):
        if text == "Mydro":
            self.dockwidget.subcatsLabel.setText("Subcats: ID, Area_km2, HillLen, HillSlope, FracImp, Downstream")
            self.dockwidget.streamsLabel.setEnabled(True)
            self.dockwidget.streamsLabel.setText("Streams: ID, Length_km, Slope_m_m")
        elif text == "URBS":
            self.dockwidget.subcatsLabel.setText("Subcats: ID, Area_km2, Downstream - Optional:(CatSlope,FracImp,FracUrban,FracForest)")
            self.dockwidget.streamsLabel.setEnabled(True)
            self.dockwidget.streamsLabel.setText("Streams: ID, Length_km, Slope_m_m")
        elif text == "RORB":
            self.dockwidget.subcatsLabel.setText("Subcats: ID, Area_km2, FracImp, Downstream")
            self.dockwidget.streamsLabel.setEnabled(True)
            self.dockwidget.streamsLabel.setText("Streams: ID, Length_km")
        elif text == "WBNM":
            self.dockwidget.subcatsLabel.setText("Subcats: ID, Area_km2, FracImp, Downstream")
            self.dockwidget.streamsLabel.setEnabled(True)
            self.dockwidget.streamsLabel.setText("Streams: NONE")
            self.dockwidget.streamsLabel.setEnabled(False)
    
    def runDelineation(self):
        demLayer = self.dockwidget.dem.currentLayer()
        if demLayer is None:
            self.iface.messageBar().pushMessage("ERROR", "Select a valid DEM layer.", level=Qgis.Critical, duration=6)
            return
        if demLayer.providerType() != "gdal":
            self.iface.messageBar().pushMessage("WARNING", "DEM must GDAL compatible and not a memory/scratch layer", level=Qgis.Warning, duration=6)
            
        outletsLayer = self.dockwidget.outletsLayer.currentLayer()
        if outletsLayer.providerType() != "ogr":
            self.iface.messageBar().pushMessage("WARNING", "Outlets layer must be OGR compatible", level=Qgis.Warning, duration=6)
        
        carveLayer = self.dockwidget.carveLayer.currentLayer()
        carvePath = 0
        if carveLayer != None:
            if carveLayer.providerType() != "ogr":
                self.iface.messageBar().pushMessage("WARNING", "Carve layer must be OGR compatible", level=Qgis.Warning, duration=6)
            carvePath = str(carveLayer.source())
            
        outputPath = (self.dockwidget.delinDir.filePath() or "").strip()
        if not outputPath:
            self.iface.messageBar().pushMessage("ERROR", "Output directory must be specified", level=Qgis.Critical, duration=6)
            return
        model = self.dockwidget.targetModel.currentText()
        
        subcatSize = self.dockwidget.subcatSize.value() if self.dockwidget.toggle_autoBreakup.isChecked() else 0
        
        template_batch_file = os.path.join(self.plugin_dir, "scripts//templateRunQMydro.bat")
        with open(template_batch_file, 'r') as file:
            template_content = file.read()
        
        batch_content = template_content.replace('%1', str(demLayer.source()).split('|')[0])
        batch_content = batch_content.replace('%2', str(carvePath).split('|')[0])
        batch_content = batch_content.replace('%3', str(outletsLayer.source()).split('|')[0])
        batch_content = batch_content.replace('%4', str(outputPath).split('|')[0])
        batch_content = batch_content.replace('%5', str(subcatSize))
        batch_content = batch_content.replace('%6', model)
        batch_content = batch_content.replace('%7', os.path.join(self.plugin_dir,"scripts","QMydro.exe"))
        
        generated_batch_file = os.path.join(outputPath, 'runQMydro.bat')
        with open(generated_batch_file, 'w') as file:
            file.write(batch_content)
            
        worker = SubprocessWorker(generated_batch_file,self.plugin_dir)
        worker.signals.finished.connect(self.on_finished_qmydro)
        QThreadPool.globalInstance().start(worker)
        self.dockwidget.runDelineation.setText("QMYDRO RUNNING - PLEASE SEE EXTERNAL COMMAND PROMPT WINDOW")
        self.dockwidget.runDelineation.setEnabled(False)
        
        return
        
    def write_nodalLinks(self, subcatsLayer, outpath):
        epsgCode = subcatsLayer.crs().authid().split(":")[1]
        nodalLinks_layer = QgsVectorLayer(f"LineString?crs=EPSG:{epsgCode}", "NodalLinks", "memory")
        pr = nodalLinks_layer.dataProvider()

        pr.addAttributes([
            QgsField("FromID", QVariant.String),
            QgsField("ToID", QVariant.String),
        ])
        nodalLinks_layer.updateFields()
    
        id_to_centroid = {}
        for f in subcatsLayer.getFeatures():
            geom = f.geometry()
            if not geom or geom.isEmpty():
                continue
    
            c = geom.centroid()
            if not c or c.isEmpty():
                continue
    
            fid_val = f["ID"]
            if fid_val is None:
                continue
    
            pt = QgsPoint(geom.centroid().asPoint())
            id_to_centroid[str(fid_val)] = pt
    
        for f in subcatsLayer.getFeatures():
            from_id = f["ID"]
            to_id = f["Downstream"]
    
            if from_id is None or to_id is None or to_id == -1:
                continue
    
            from_id_s = str(from_id)
            to_id_s = str(to_id)
    
            if to_id_s.strip() == "" or to_id_s.lower() in ("none", "null"):
                continue
            if from_id_s == to_id_s:
                continue
    
            p_from = id_to_centroid.get(from_id_s)
            p_to = id_to_centroid.get(to_id_s)
    
            # If downstream feature not found, just skip
            if p_from is None or p_to is None:
                continue
    
            lf = QgsFeature(nodalLinks_layer.fields())
            line = QgsGeometry.fromPolyline([p_from, p_to])
            lf.setGeometry(line)
            lf["FromID"] = from_id_s
            lf["ToID"] = to_id_s
            pr.addFeatures([lf])
            
        nodalLinks_layer.commitChanges()
        nodalLinks_layer.updateExtents()
        options = QgsVectorFileWriter.SaveVectorOptions()
        options.driverName = "ESRI Shapefile"

        QgsVectorFileWriter.writeAsVectorFormatV3(
            nodalLinks_layer,
            outpath,
            QgsProject.instance().transformContext(),
            options
        )
    
    def on_finished_qmydro(self):
        outputPath = (self.dockwidget.delinDir.filePath() or "").strip()
        self.dockwidget.runDelineation.setText("Run Subcatchment Breakup :]")
        self.dockwidget.runDelineation.setEnabled(True)
        
        if not (os.path.exists(os.path.join(outputPath, "QMydro_DrainageDir.tif"))):
            self.iface.messageBar().pushMessage("Error", "QMydro did not finish execution - exitted QMydro process", level=Qgis.Critical)
            return
        
        # Output Files
        shutil.copy(os.path.join(self.plugin_dir, "styles", "accumStyle.qml"),os.path.join(outputPath, "QMydro_Accumulation.qml"))
        accumLayer = QgsRasterLayer(os.path.join(outputPath, "QMydro_Accumulation.tif"), "QMydro_Accumulation")
        QgsProject.instance().addMapLayer(accumLayer)
        
        shutil.copy(os.path.join(self.plugin_dir, "styles", "streamsStyle.qml"),os.path.join(outputPath, "QMydro_Streams.qml"))
        streamsLayer = QgsVectorLayer(os.path.join(outputPath, "QMydro_Streams.shp"), "QMydro_Streams")
        streamsLayer.loadNamedStyle(os.path.join(self.plugin_dir, "styles", "streamsStyle.qml"))
        QgsProject.instance().addMapLayer(streamsLayer)
        
        shutil.copy(os.path.join(self.plugin_dir, "styles", "subcatsStyle.qml"),os.path.join(outputPath, "QMydro_Subcats.qml"))
        subcatsLayer = QgsVectorLayer(os.path.join(outputPath, "QMydro_Subcats.shp"), "QMydro_Subcats")
        subcatsLayer.loadNamedStyle(os.path.join(self.plugin_dir, "styles", "subcatsStyle.qml"))
        QgsProject.instance().addMapLayer(subcatsLayer)
        
        nodalOutputPath = os.path.join(outputPath, "QMydro_NodalLinks.shp")
        nodalQmlPath = os.path.splitext(nodalOutputPath)[0] + ".qml"
        shutil.copy(
            os.path.join(self.plugin_dir, "styles", "nodalStyle.qml"),
            nodalQmlPath
        )
        nodalLinksLayer = QgsVectorLayer(nodalOutputPath, os.path.splitext(os.path.basename(nodalOutputPath))[0])
        nodalLinksLayer.loadNamedStyle(nodalQmlPath)
        QgsProject.instance().addMapLayer(nodalLinksLayer)
        
        outputPath = (self.dockwidget.delinDir.filePath() or "").strip()
        err = convertToURBS.convert_to_URBS(outputPath,
                                        os.path.join(outputPath,"QMydro_SubCats.shp"),
                                        os.path.join(outputPath,"QMydro_Streams.shp")
                                        )
        if err != None:
            self.iface.messageBar().pushMessage("Error", err, level=Qgis.Critical)
            
        if self.dockwidget.targetModel.currentText() == "RORB":
            convertToRORB.convert_to_RORB(os.path.join(outputPath,"_RORB.catg"),
                os.path.join(outputPath,"QMydro_SubCats.shp"),
                os.path.join(outputPath,"URBS_RoutingFile.vec"))
        
        if self.dockwidget.targetModel.currentText() == "WBNM":
            convertToWBNM.convert_to_WBNM(os.path.join(outputPath,"_WBNM.wbn"),
                os.path.join(outputPath,"QMydro_SubCats.shp"),
                os.path.join(outputPath,"URBS_RoutingFile.vec")) 
        
    
    def recalculate(self):
        
        model = self.dockwidget.recalcModel.currentText()
        outputPath = (self.dockwidget.recalcDest.filePath() or "").strip()
        subcatsLayer = self.dockwidget.subcatsLayer.currentLayer()
        streamsLayer = self.dockwidget.streamsLayer.currentLayer()
        
        if not outputPath:
            self.iface.messageBar().pushMessage("ERROR", "Output directory must be specified", level=Qgis.Critical, duration=6)
            return
        
        if not subcatsLayer:
            self.iface.messageBar().pushMessage("ERROR", "Subcatchment Shapefile must be specified", level=Qgis.Critical, duration=6)
            return        
        
        if model == "URBS" or model == "RORB" or model == "Mydro":
            if not self.dockwidget.streamsLayer.currentLayer():
                self.iface.messageBar().pushMessage("ERROR", "Stream line Shapefile must be specified", level=Qgis.Critical, duration=6)
                return
    
        err = convertToURBS.convert_to_URBS(outputPath,
                                        str(subcatsLayer.source()).split('|')[0],
                                        streamsLayer.source()
                                        )
        if err != None:
            self.iface.messageBar().pushMessage("Error", err, level=Qgis.Critical)
            
        if model == "RORB":
            convertToRORB.convert_to_RORB(os.path.join(outputPath,"_RORB.catg"),
                str(subcatsLayer.source()).split('|')[0],
                os.path.join(outputPath,"URBS_RoutingFile.vec"))
        
        if model == "WBNM":
            convertToWBNM.convert_to_WBNM(os.path.join(outputPath,"_WBNM.wbn"),
                str(subcatsLayer.source()).split('|')[0],
                os.path.join(outputPath,"URBS_RoutingFile.vec")) 
        
        nodalOutputPath = os.path.join(outputPath, "QMydro_NodalLinks.shp")

        i = 1
        base, ext = os.path.splitext(nodalOutputPath)
        while os.path.exists(nodalOutputPath):
            nodalOutputPath = f"{base}_{i}{ext}"
            i += 1
        self.write_nodalLinks(subcatsLayer, nodalOutputPath)
        nodalQmlPath = os.path.splitext(nodalOutputPath)[0] + ".qml"
        shutil.copy(
            os.path.join(self.plugin_dir, "styles", "nodalStyle.qml"),
            nodalQmlPath
        )
        nodalLinksLayer = QgsVectorLayer(nodalOutputPath, os.path.splitext(os.path.basename(nodalOutputPath))[0])
        nodalLinksLayer.loadNamedStyle(nodalQmlPath)
        QgsProject.instance().addMapLayer(nodalLinksLayer)
        
        if err == None:
            self.iface.messageBar().pushMessage("QMydro", "Finished Recalculation", Qgis.Success)
        
    def run(self):
        """Run method that loads and starts the plugin"""

        if not self.pluginIsActive:
            self.pluginIsActive = True
            if self.dockwidget == None:
                # Create the dockwidget (after translation) and keep reference
                self.dockwidget = QMydroDockWidget()

            self.dockwidget.closingPlugin.connect(self.onClosePlugin)
            self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockwidget)
            self.dockwidget.show()
            
            # Do Things:
            
            # -------------------------------- Delineation -----------------------------------------
            self.dockwidget.dem.setFilters(QgsMapLayerProxyModel.RasterLayer)
            self.dockwidget.dem.setCurrentIndex(-1)
            
            self.dockwidget.carveLayer.setFilters(QgsMapLayerProxyModel.LineLayer)
            self.dockwidget.carveLayer.setCurrentIndex(-1)
            
            self.dockwidget.outletsLayer.setFilters(QgsMapLayerProxyModel.LineLayer)
            self.dockwidget.outletsLayer.setCurrentIndex(-1)
            
            self.dockwidget.delinDir.setDialogTitle('Select Output Directory')
            
            self.dockwidget.toggle_autoBreakup.setChecked(False)
            self.dockwidget.toggle_autoBreakup.stateChanged.connect(self.toggleBreakup)
            
            itemList = ["Mydro","URBS","RORB","WBNM"]
            self.dockwidget.targetModel.clear()
            self.dockwidget.targetModel.addItems(itemList)
            self.dockwidget.targetModel.setCurrentIndex(1)
            
            self.dockwidget.runDelineation.clicked.connect(self.runDelineation)
            
            # --------------------------------- Recalculate ----------------------------------------
            self.dockwidget.subcatsLayer.setFilters(QgsMapLayerProxyModel.PolygonLayer)
            self.dockwidget.subcatsLayer.setCurrentIndex(-1)
            
            self.dockwidget.streamsLayer.setFilters(QgsMapLayerProxyModel.LineLayer)
            self.dockwidget.streamsLayer.setCurrentIndex(-1)
            
            itemList = ["Mydro","URBS","RORB","WBNM"]
            self.dockwidget.recalcModel.clear()
            self.dockwidget.recalcModel.addItems(itemList)
            self.dockwidget.recalcModel.setCurrentIndex(1)
            self.dockwidget.recalcModel.currentTextChanged.connect(self.UpdateRecalcRequirements)
            
            self.dockwidget.recalculate.clicked.connect(self.recalculate)
            