# -*- coding: utf-8 -*-

"""
/***************************************************************************
 NetworkCleanup
                                 A QGIS plugin
 A collection of tools to help fix network topology.
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2026-02-12
        copyright            : (C) 2026 by Thomas Raj
        email                : lemungineer@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.                                   *
 *                                                                         *
 ***************************************************************************/
"""

__author__ = 'Thomas Raj'
__date__ = '2026-02-12'
__copyright__ = '(C) 2026 by Thomas Raj'

# This will get replaced with a git SHA1 when you do a git archive

__revision__ = '$Format:%H$'

import os

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (
    QgsProcessing,
    QgsFeatureSink,
    QgsProcessingAlgorithm,
    QgsProcessingParameterFeatureSource,
    QgsProcessingParameterFeatureSink,
    QgsProcessingParameterField,
    QgsFeatureRequest,
    QgsProcessingParameterBoolean,
    QgsProcessingParameterNumber,
    QgsProcessingParameterVectorLayer
)

from qgis.PyQt.QtGui import QIcon

from .logic.loop_check import loop_checker


class loopCheckingAlgorithm(QgsProcessingAlgorithm):

    INPUT = 'INPUT'
    OUTPUT = 'OUTPUT'
    ID_FIELD = 'ID_FIELD'

    def initAlgorithm(self, config):

        # Input line layer
        self.addParameter(
            QgsProcessingParameterVectorLayer(
                self.INPUT,
                self.tr('Input layer'),
                [QgsProcessing.TypeVectorLine]
            )
        )

        # Field to use as ID (e.g. name, corridor ID, pipe ID, etc)
        self.addParameter(
            QgsProcessingParameterField(
                self.ID_FIELD,
                self.tr('Loop Field'),
                parentLayerParameterName=self.INPUT,
                type=QgsProcessingParameterField.Any
            )
        )

        # Output
        self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.OUTPUT,
                self.tr('Loops')
            )
        )

    def processAlgorithm(self, parameters, context, feedback):
        # Use the actual project layer
        layer = self.parameterAsVectorLayer(parameters, self.INPUT, context)

        id_field = self.parameterAsString(parameters, self.ID_FIELD, context)


        #feedback.pushInfo(f"Using ID field: {id_field}")

        # Run your tee junction pipeline
        result_layer = loop_checker(layer=layer, loop_field=id_field)

        # Create sink with the fields, geometry type and CRS of the output layer
        sink, dest_id = self.parameterAsSink(
            parameters,
            self.OUTPUT,
            context,
            result_layer.fields(),
            result_layer.wkbType(),
            result_layer.sourceCrs()
        )

        # Add resulting features to sink
        for f in result_layer.getFeatures():
            if feedback.isCanceled():
                break
            sink.addFeature(f, QgsFeatureSink.FastInsert)

        return {self.OUTPUT: dest_id}


    def name(self):
        return 'loop_check'

    def displayName(self):
        return self.tr('Loop Check')

    def group(self):
        return self.tr(self.groupId())

    def tr(self, string):
        return QCoreApplication.translate('Processing', string)

    def shortHelpString(self):
        return self.tr("""
    This purpose of this algorithm is to ensure that all loops within a system are fully connected.
                       
    Start by creating an empty column in your network layer. Fill that column with a value (any value will do) for any line that is part of a loop.
                       
    Once done, run this algorithm and a layer will be returned. Each line in this layer should be a continuous until it meets another line.
    
    If they aren't continuous, there's a discontinuity in the loops within the network, fix any identifed areas and repeat until all loops are interconnected.
    """)


    def createInstance(self):
        return loopCheckingAlgorithm()