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

"""
/***************************************************************************
 LRS -Linear Referencing System
                                 A QGIS plugin
 
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2022-04-02
        copyright            : (C) 2022 by Iñigo Marin
        email                : proy.mbr@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__ = 'Iñigo Marin'
__date__ = '2022-04-02'
__copyright__ = '(C) 2022 by Iñigo Marin'

# 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
from qgis.core import QgsProcessingAlgorithm
from qgis.core import QgsProcessingMultiStepFeedback
from qgis.core import QgsProcessingParameterNumber
from qgis.core import QgsProcessingParameterRasterLayer
from qgis.core import QgsProcessingParameterVectorLayer
from qgis.core import QgsProcessingParameterPoint
from qgis.core import QgsProcessingParameterRasterDestination
from qgis.core import QgsProcessingParameterVectorDestination
from qgis.core import QgsProcessingParameterFeatureSink
from qgis.core import QgsProcessingParameterMapLayer
from qgis.core import QgsProcessingParameterFeatureSink
from qgis.core import QgsExpression
from qgis.core import QgsMessageLog
from qgis.gui import QgsMessageBar
from qgis.core import Qgis
from os import path
from PyQt5.QtGui import QIcon
import processing


class LRSAlgorithm(QgsProcessingAlgorithm):

    OUTPUT = 'OUTPUT'
    INPUT = 'INPUT'
    
    
    def initAlgorithm(self, config=None):
    
        # Seleccion la capa para dibujar pKs
    
        self.addParameter(QgsProcessingParameterMapLayer('input_vector_layer', 'Input line vector layer', defaultValue=None, types=[QgsProcessing.TypeVectorLine]))
        self.addParameter(QgsProcessingParameterFeatureSink('output_vector_layer', 'Output point vector layer with LRS marks & text', type=QgsProcessing.TypeVectorPoint, createByDefault=True, supportsAppend=True, defaultValue=None))

    def processAlgorithm(self, parameters, context, model_feedback):
    
        # Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
        # overall progress through the model
        
        feedback = QgsProcessingMultiStepFeedback(2, model_feedback)
        results = {}
        outputs = {}

        # Points along geometry
        # Algoritmo de creación de puntos con Pks
        
        alg_params = {
            'DISTANCE': 25,
            'END_OFFSET': 0,
            'INPUT': parameters['input_vector_layer'],
            'START_OFFSET': 0,
            'OUTPUT': parameters['output_vector_layer']
        }
        
        outputs['PointsAlongGeometry'] = processing.run('native:pointsalonglines', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        results['output_vector_layer'] = outputs['PointsAlongGeometry']['OUTPUT']

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        # Set layer style
        # Asigna el estilo de Pks
        
        alg_params = {
            'INPUT': outputs['PointsAlongGeometry']['OUTPUT'],
            'STYLE': path.dirname(__file__) +'/LRS_Style.qml' 
        }              
        
        outputs['SetLayerStyle'] = processing.run('native:setlayerstyle', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        
  
        return results

    def name(self):
        """
        Returns the algorithm name, used for identifying the algorithm. This
        string should be fixed for the algorithm, and must not be localised.
        The name should be unique within each provider. Names should contain
        lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return 'LRS'

    def icon(self):
        """
        Should return a QIcon which is used for your provider inside
        the Processing toolbox.
        """
        return QIcon(path.dirname(__file__) +'/LRS.png')
    
    def displayName(self):
        """
        Returns the translated algorithm name, which should be used for any
        user-visible display of the algorithm name.
        """
        return self.tr(self.name())

    def group(self):
        """
        Returns the name of the group this algorithm belongs to. This string
        should be localised.
        """
        return self.tr(self.groupId())

    def groupId(self):
        """
        Returns the unique ID of the group this algorithm belongs to. This
        string should be fixed for the algorithm, and must not be localised.
        The group id should be unique within each provider. Group id should
        contain lowercase alphanumeric characters only and no spaces or other
        formatting characters.
        """
        return ''

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

    def shortHelpString(self):
        return """<html><body><p>LRS creates the linear referencing marks and text for each 25 and 100 m. intervals, based on and existing line/polyline (vector file), using the "Points along geometry" algorithm" .</p>
<h2>Input parameters</h2>
<h3>Input line vector layer</h3>
<p>Input line vector layer representing an axis</p>
<h2>Outputs</h2>
<h3>Output point vector layer with LRS marks & text</h3>
<p>Output vector Point layer with an associated style representing the linear referencing marks and text for each 25 and 100 m. intervals</p>
<br><p align="right">Algorithm author: Iñigo Marin</p><p align="right">Algorithm version: v. 0.1</p></body></html>"""

    def helpUrl(self):
        return 'https://github.com/MBR111/CivilEng'
        
    def createInstance(self):
        return LRSAlgorithm()
