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

"""
/***************************************************************************
 DeepLearningTools
                                 A QGIS plugin
 QGIS plugin to aid training Deep Learning Models
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2020-03-12
        copyright            : (C) 2020 by Philipe Borba
        email                : philipeborba@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.                                   *
 *                                                                         *
 ***************************************************************************/
"""

import os
import itertools
from pathlib import Path
from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsProcessingParameterField,
                       QgsProcessingParameterVectorLayer,
                       QgsProcessingParameterMultipleLayers,
                       QgsProcessingParameterBoolean,
                       QgsProcessingException,
                       QgsProcessingParameterNumber,
                       QgsProcessingMultiStepFeedback,
                       QgsFeatureRequest
                       )
from DeepLearningTools.core.image_processing.vector_utils import VectorUtils
import concurrent.futures


class CreateGridAlgorithm(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.
    INPUT = 'INPUT'
    SELECTED = 'SELECTED'
    OUTPUT = 'OUTPUT'
    INPUT_POLYGONS = 'INPUT_POLYGONS'
    NUM_CPU = 'NUM_CPU'
    NUM_FEATS = 'NUM_FEATS'

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

        # We add the input vector features source. It can have any kind of
        # geometry.
        self.addParameter(
            QgsProcessingParameterVectorLayer(
                self.INPUT,
                self.tr('Input layer'),
                [QgsProcessing.TypeVectorPolygon]
            )
        )

        self.addParameter(
            QgsProcessingParameterBoolean(
                self.SELECTED,
                self.tr('Process only selected features')
            )
        )

        self.addParameter(
            QgsProcessingParameterMultipleLayers(
                self.INPUT_POLYGONS,
                self.tr('Input polygons'),
                QgsProcessing.TypeVectorPolygon
            )
        )

        self.addParameter(
            QgsProcessingParameterNumber(
                self.NUM_CPU,
                self.tr('Number of CPUs used in processing'),
                QgsProcessingParameterNumber.Integer,
                defaultValue=1,
                minValue=1,
                maxValue=os.cpu_count()
            )
        )
        self.addParameter(
            QgsProcessingParameterNumber(
                self.NUM_FEATS,
                self.tr('Number of features fetched per thread'),
                QgsProcessingParameterNumber.Integer,
                defaultValue=10000,
                minValue=1
            )
        )

        self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.OUTPUT,
                self.tr('Output layer')
            )
        )


    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.
        inputLyr = self.parameterAsVectorLayer(
            parameters,
            self.INPUT,
            context
        )
        if inputLyr is None:
            raise QgsProcessingException(
                self.invalidSourceError(
                    parameters,
                    self.INPUT
                )
            )
        onlySelected = self.parameterAsBool(
            parameters,
            self.SELECTED,
            context
        )
        featCount = inputLyr.featureCount() if not onlySelected \
            else inputLyr.selectedFeatureCount()
        features = inputLyr.getFeatures() if not onlySelected \
            else inputLyr.getSelectedFeatures()
        # Compute the number of steps to display within the progress bar and
        # get features from source
        self.total = 100.0 / featCount if featCount else 0

        (sink, dest_id) = self.parameterAsSink(
            parameters,
            self.OUTPUT,
            context,
            inputLyr.fields(),
            inputLyr.wkbType(),
            inputLyr.sourceCrs()
        )

        vector_utils = VectorUtils()
        inputPolygonsLyrList = self.parameterAsLayerList(
            parameters,
            self.INPUT_POLYGONS,
            context
        )
        if inputPolygonsLyrList == []:
            raise QgsProcessingException(
                self.invalidSourceError(
                    parameters,
                    self.INPUT_POLYGONS
                )
            )
        num_workers = self.parameterAsInt(
            parameters,
            self.NUM_CPU,
            context
        )
        num_feats_per_worker = self.parameterAsInt(
            parameters,
            self.NUM_FEATS,
            context
        )
        def compute(feature):
            geom = feature.geometry()
            request = QgsFeatureRequest()
            request.setFilterRect(geom.boundingBox())
            # for lyr in inputPolygonsLyrList:
            featList = map(
                lambda x: x.getFeatures(request),
                inputPolygonsLyrList
            )
            for feat in itertools.chain.from_iterable(featList):
                if feedback is not None and feedback.isCanceled():
                    return
                if geom.intersects(feat.geometry()):
                    sink.addFeature(
                        feature,
                        QgsFeatureSink.FastInsert
                    )
                    break
            self.current_feat += 1
            if feedback is not None:
                feedback.setProgress(
                    int(self.current_feat * self.total)
                )
            return

        self.current_feat = 0
        with concurrent.futures.ThreadPoolExecutor() as executor:
            futures = {
                executor.submit(compute, task): task
                for task in itertools.islice(features, num_feats_per_worker)
            }
            while futures:
                if feedback is not None and feedback.isCanceled():
                    break
                # Wait for the next future to complete.
                done, futures = concurrent.futures.wait(
                    futures, return_when=concurrent.futures.FIRST_COMPLETED
                )

                # Schedule the next set of futures.  We don't want more than N futures
                # in the pool at a time, to keep memory consumption down.
                for task in itertools.islice(features, len(done)):
                    futures.add(
                        executor.submit(compute, task)
                    )
            done, futures = concurrent.futures.wait(
                    futures, return_when=concurrent.futures.ALL_COMPLETED
                )
            return {self.OUTPUT : dest_id}
    
    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 'Create Create Grid that intersect label data'

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

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

    def createInstance(self):
        return CreateGridAlgorithm()
