# -*- 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$'

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

from qgis.core import QgsProject

import processing

from .logic.extract_merge_selected_features import *

class mergeSelectedFeatureLayers(QgsProcessingAlgorithm):

    LINE_LAYERS = 'LINE_LAYERS'
    POLYGON_LAYERS = 'POLYGON_LAYERS'
    POINT_LAYERS = 'POINT_LAYERS'
    LOAD_LAYERS = 'LOAD_LAYERS'
    OUTPUT = 'OUTPUT'

    def initAlgorithm(self, config):

        # Input line layer

        self.addParameter(
            QgsProcessingParameterMultipleLayers(
                name=self.LINE_LAYERS,
                description='Select Line Layers',
                layerType=QgsProcessing.TypeVectorLine,
                optional=True
            )
        )
        
        self.addParameter(
            QgsProcessingParameterMultipleLayers(
                name=self.POINT_LAYERS,
                description='Select Point Layers',
                layerType=QgsProcessing.TypeVectorPoint,
                optional=True
            )
        )
        
        self.addParameter(
            QgsProcessingParameterMultipleLayers(
                name=self.POLYGON_LAYERS,
                description='Select Polygon Layers',
                layerType=QgsProcessing.TypeVectorPolygon,
                optional=True
            )
        )
        
        self.addParameter(QgsProcessingParameterBoolean(
            self.LOAD_LAYERS, 'Load Layers?',
            defaultValue=True
        ))
        
        self.addParameter(QgsProcessingParameterFileDestination(
                self.OUTPUT,
                'Output GeoPackage File',
                fileFilter='GeoPackage (*.gpkg)'
            )
        )
        
    def processAlgorithm(self, parameters, context, feedback):
        # Use the actual project layer
        line_layers = self.parameterAsLayerList(parameters, self.LINE_LAYERS, context)
        point_layers = self.parameterAsLayerList(parameters, self.POINT_LAYERS, context)
        polygon_layers = self.parameterAsLayerList(parameters, self.POLYGON_LAYERS, context)
        
        load_layers = self.parameterAsBool(parameters, self.LOAD_LAYERS, context)
        gpkg_path = self.parameterAsFileOutput(parameters, self.OUTPUT, context)
        
        selected_merged_layers = []
        
        if line_layers:
            merged_line_layers = extract_merge_selected_features(layer_list=line_layers,layer_name='Line Layers Merged')
            selected_merged_layers.append(merged_line_layers)
            
        if point_layers:
            merged_point_layers = extract_merge_selected_features(layer_list=point_layers,layer_name='Point Layers Merged')
            selected_merged_layers.append(merged_point_layers)
            
        if polygon_layers:
            merged_polygon_layers = extract_merge_selected_features(layer_list=polygon_layers,layer_name='Polygon Layers Merged')
            selected_merged_layers.append(merged_polygon_layers)
            
        processing.run("native:package", {'LAYERS':selected_merged_layers,'OUTPUT':gpkg_path,'OVERWRITE':False,'SAVE_STYLES':True,'SAVE_METADATA':True,'SELECTED_FEATURES_ONLY':False,'EXPORT_RELATED_LAYERS':False})
        
        if load_layers:
            
            for layer in selected_merged_layers:
                QgsProject.instance().addMapLayer(layer)
        
        return {}

    def name(self):
        return 'merge_selected_feature_layers'

    def displayName(self):
        return self.tr('Merge Selected Feature Layers')

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

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

    def shortHelpString(self):
        return self.tr("""
    This algorithm merges selected features from multiple layers into one layer.
    """)

    def createInstance(self):
        return mergeSelectedFeatureLayers()