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

"""
/***************************************************************************
 Networks
                                 A QGIS plugin
 Networks
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2018-02-26
        copyright            : (C) 2018 by Patrick Palmier
        email                : patrick.palmier@cerema.fr
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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__ = 'Patrick Palmier'
__date__ = '2018-02-26'
__copyright__ = '(C) 2018 by Patrick Palmier'

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

__revision__ = '$Format:%H$'

from qgis.PyQt.QtCore import QCoreApplication,QVariant
from qgis.core import *
from qgis.utils import *
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsProcessingParameterNumber,
                       QgsProcessingParameterBoolean,
                       QgsProcessingParameterString,
                       QgsProcessingParameterExtent,
                       QgsProcessingParameterField,
                       QgsProcessingParameterExpression,
                       QgsProcessingParameterFileDestination,
                       QgsSpatialIndex,
                       QgsGeometry,
                       QgsFeature
                       )
import codecs

class ConnectNodes2Lines(QgsProcessingAlgorithm):
    """
    This is an example algorithm that takes a vector layer and
    creates a new identical one.

    It is meant to be used as an example of how to create your own
    algorithms and explain methods and variables used to do it. An
    algorithm like this will be available in all elements, and there
    is not need for additional work.

    All Processing algorithms should extend the QgsProcessingAlgorithm
    class.
    """

    # Constants used to refer to parameters and outputs. They will be
    # used when calling the algorithm from another algorithm, or when
    # calling from the QGIS console.

    LINES = 'LINES'
    NODES = 'NODES'
    RAYON='RAYON'

    def initAlgorithm(self, config):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """

        self.addParameter(
            QgsProcessingParameterVectorLayer(
                self.LINES,
                self.tr('Network(Qgis)'),
                [QgsProcessing.TypeVectorLine]
            )
        )
        self.addParameter(
            QgsProcessingParameterVectorLayer(
                self.NODES,
                self.tr('Nodes(Qgis)'),
                [QgsProcessing.TypeVectorPoint]
            )
        )
        self.addParameter(
            QgsProcessingParameterNumber(
                self.RAYON,
                self.tr('Radius(m)'),
                QgsProcessingParameterNumber.Double,
                defaultValue=1000
            )
        )

        # We add a feature sink in which to store our processed features (this
        # usually takes the form of a newly created vector layer when the
        # algorithm is run in QGIS).
        

    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """

        # Retrieve the feature source and sink. The 'dest_id' variable is used
        # to uniquely identify the feature sink, and must be included in the
        # dictionary returned by the processAlgorithm function.
        couche_lines = self.parameterAsVectorLayer(parameters, self.LINES, context)
        couche_points = self.parameterAsVectorLayer(parameters, self.NODES, context)
        radius=self.parameterAsDouble(parameters,self.RAYON,context)

        # Compute the number of steps to display within the progress bar and
        # get features from source
        delta=float(radius)
        index=QgsSpatialIndex(couche_lines.getFeatures())


        couche_lines.startEditing()
        couche_lines.beginEditCommand(self.tr("Split polylines at connections"))
        points=couche_points.getFeatures()
        nb=couche_points.featureCount()
        feedback.setProgressText(self.tr("Connecting points to lines..."))
        for pos,pt in enumerate(points):
            feedback.setProgress(pos*100.0/nb)
            ptg=pt.geometry()
            ptg.convertToSingleType()

            coor=ptg.asPoint()
            nearest=index.intersects(QgsRectangle(coor.x()-delta,coor.y()-delta,coor.x()+delta,coor.y()+delta))
            dmin=1e38
            if len(nearest)>0:
                for n in nearest:
                    f=couche_lines.getFeatures(request=QgsFeatureRequest(n))
                    for gg in f:
                        d=pt.geometry().distance(gg.geometry())
                        if d<=dmin:
                            dmin=d
                            gmin=gg
                            gid=gg.id()
                g=gmin
                if g.geometry().distance(pt.geometry())<delta:
                    a=g.geometry().closestSegmentWithContext(ptg.asPoint())
                    if a[2]>=0:
                        geom=g.geometry()
                        geom.convertToSingleType()
                        geom_id=g.id()
                        att=g.attributes()
                        connexion=QgsFeature()

                        connexion.setGeometry(QgsGeometry.fromPolylineXY([ptg.asPoint(),a[1]]))
                        connexion.geometry().convertToMultiType()
                        connexion.setAttributes(att)
                        if connexion.geometry().length()>0:
                            couche_lines.dataProvider().addFeatures([connexion])
                        
                        geom.insertVertex(a[1][0],a[1][1],a[2])
                        geoma=geom.asPolyline()[:a[2]+1]
                        geomb=geom.asPolyline()[a[2]:]
                        #feedback.setProgressText(unicode(geomb))
                        fa=QgsFeature()
                        fa.setGeometry(QgsGeometry.fromPolylineXY(geoma))
                        fa.geometry().convertToMultiType()
                        fa.setAttributes(att)
                        if fa.geometry().length()>0:
                            couche_lines.dataProvider().addFeatures([fa])
                        
                        fb=QgsFeature()
                        fb.setGeometry(QgsGeometry.fromPolylineXY(geomb))
                        fb.geometry().convertToMultiType()
                        fb.setAttributes(att)
                        if fb.geometry().length()>0:
                            couche_lines.dataProvider().addFeatures([fb])
                        
                        
                        couche_lines.dataProvider().deleteFeatures([g.id()])
                        
                        index.deleteFeature(g)
                        index=QgsSpatialIndex(couche_lines.getFeatures())
        couche_lines.commitChanges()
        couche_lines.endEditCommand()
        return {self.LINES: 'OK'}


    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 'connect_nodes2lines'

    def displayName(self):
        """
        Returns the translated algorithm name, which should be used for any
        user-visible display of the algorithm name.
        """
        return self.tr('Connect nodes to lines')

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

    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 'Network'
		
    def shortHelpString(self):
        return self.tr("""
        Connect points to a a linear objetcs layers within a search radius. Points are conencted to the closest line. 
        The closest line is splitted at the shorstest distance point in two lines, and a line is generated between the point and the closest point
        The lines layer is in editable mode in order to be alble to cancel the connections.
        
        Parameters:
            lines : lines layer (linear objects)
			nodes: points layer
            radius: search radius (m)
        """)
    
    def tr(self, string):
        return QCoreApplication.translate('ConnectNodes2Lines', string)

    def createInstance(self):
        return ConnectNodes2Lines()
