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

"""
/***************************************************************************
 Visualist
                                 A QGIS plugin
 Plugin for Crime Analysts
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2019-04-15
        copyright            : (C) 2019 by Quentin Rossy
        email                : quentin.rossy@unil.ch
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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__ = 'Quentin Rossy'
__date__ = '2019-04-15'
__copyright__ = '(C) 2019 by Quentin Rossy'

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

__revision__ = '$Format:%H$'

from qgis.core import (QgsProcessing,
                        QgsProcessingMultiStepFeedback,
                        QgsProcessingParameterFeatureSource,
                        QgsProcessingParameterFeatureSink,
                        QgsProcessingParameterDistance,
                        QgsProcessingParameterField,
                        QgsProcessingParameterString,
                        QgsProcessingParameterDefinition)

from .visualist_alg import VisualistAlgorithm
from tempfile import gettempdir
import processing, os

class PointsToSplitLine(VisualistAlgorithm):

    LINES = 'LINES'
    SEGMENT_SIZE = 'SEGMENT_SIZE'
    POINTS = 'POINTS'
    DIST = 'DIST'
    FIELD = 'FIELD'
    POINTS_ROAD_NAMES = 'POINTS_ROAD_NAMES'
    LINES_ROAD_NAMES = 'LINES_ROAD_NAMES'
    OUTPUT_POINT = 'OUTPUT_POINT'
    OUTPUT_LINE = 'OUTPUT_LINE'

    def __init__(self):
        super().__init__()

    def name(self):
        return 'graduatedsegmentedlinemap'

    def initAlgorithm(self, config=None):

        self.addParameter(QgsProcessingParameterFeatureSource(self.LINES,
                                            self.tr('Lines'),
                                            types=[QgsProcessing.TypeVectorLine],
                                            defaultValue=None))
        self.addParameter(QgsProcessingParameterDistance(self.SEGMENT_SIZE,
                                            self.tr('Size of the segments'),
                                            parentParameterName=self.LINES,
                                            defaultValue=200))

        self.addParameter(QgsProcessingParameterFeatureSource(self.POINTS,
                                            self.tr('Point Layer'),
                                            types=[QgsProcessing.TypeVectorPoint],
                                            defaultValue=None))

        self.addParameter(QgsProcessingParameterDistance(self.DIST,
                                            self.tr('Maximum distance to the line'),
                                            parentParameterName=self.POINTS,
                                            defaultValue=100))

        lroad_fied = QgsProcessingParameterField(self.LINES_ROAD_NAMES,
                                            self.tr('Names of roads in line layer'),
                                            type=QgsProcessingParameterField.String,
                                            parentLayerParameterName=self.LINES,
                                            allowMultiple=False, defaultValue=None, optional=True)
        lroad_fied.setFlags(lroad_fied.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
        self.addParameter(lroad_fied)

        proad_field = QgsProcessingParameterField(self.POINTS_ROAD_NAMES,
                                    self.tr('Names of roads in point layer'),
                                    type=QgsProcessingParameterField.String,
                                    parentLayerParameterName=self.POINTS,
                                    allowMultiple=False, defaultValue=None, optional=True)
        proad_field.setFlags(proad_field.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
        self.addParameter(proad_field)

        count_field = QgsProcessingParameterString(self.FIELD, self.tr('Count field name'), defaultValue='NUMPOINTS')
        count_field.setFlags(count_field.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
        self.addParameter(count_field)

        self.addParameter(QgsProcessingParameterFeatureSink(self.OUTPUT_LINE,
                                                    self.tr('Graduated Segmented Lines Map'),
                                                    QgsProcessing.TypeVectorLine))
        self.addParameter(QgsProcessingParameterFeatureSink(self.OUTPUT_POINT,
                                                    self.tr('Points linked to Line Map'),
                                                    QgsProcessing.TypeVectorPoint))

    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 = {}

        # v.split
        # temporary_path = os.path.join(gettempdir(), 'segmented_layer2.gpkg')
        # Division des lignes par longueur maximale
        alg_params = {
            'INPUT': parameters[self.LINES],
            'LENGTH': parameters[self.SEGMENT_SIZE],
            'OUTPUT': 'TEMPORARY_OUTPUT'
        }
        output = processing.run('native:splitlinesbylength', alg_params, context=context, feedback=feedback, is_child_algorithm=True)
        outputs['segmentedLayer'] = output['OUTPUT']

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}
        parameters['LINES'] = outputs['segmentedLayer']
        # Graduated Lines Map
        outputs['GraduatedLinesMap'] = processing.run('visualist:graduatedlinemap', parameters, context=context, feedback=feedback, is_child_algorithm=True)
        results['LineMap'] = outputs['GraduatedLinesMap']['OUTPUT_LINE']
        return results
