# -*- 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,
    QgsProcessingParameterEnum,
    QgsField
)
from qgis.PyQt.QtCore import QVariant
from DeepLearningTools.core.image_processing.vector_utils import VectorUtils
import concurrent.futures


class FindPolygonStatisticsAlgorithm(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'
    STATS = 'STATS'

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

        self.statistics = [
            ('n_vertexes', self.tr('number of vertexes')),
            ('main_angle', self.tr('main angle of the polygon')),
            ('hole_count', self.tr('number of holes')),
            ('area', self.tr('area')),
            ('perimeter', self.tr('perimeter')),
            ('compactness', self.tr('compactness of the polygon')),
            ('fractal_dimension', self.tr('fractal dimension of the polygon')),
            ('fractality', self.tr('fractality of the polygon')),
            ('vibration_amplitude', self.tr('vibration amplitude of the polygon')),
            ('vibration_frequency', self.tr('vibration frequency of the polygon')),
            ('geometry_complexity', self.tr('gemetry complexity of the polygon')),
            ('find_feature_shape_complexity_index', self.tr('shape_complexity_index of the polygon')),
            ('equivaent_rectangular_index', self.tr('equivalent rectangular index of the polygon')),
            ('squareness', self.tr('squareness of the polygon')),
            ('circularity', self.tr('find the circularity of the polygon')),
            ('rectangularity', self.tr('find the rectangularity of the polygon'))
        ]

        # 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(
            QgsProcessingParameterEnum(
                self.STATS,
                self.tr('Statistics to calculate'),
                options=[p[1] for p in self.statistics],
                allowMultiple=True,
                optional=False
            )
        )

        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
        )

        indexList = self.parameterAsEnums(
                parameters,
                self.STATS,
                context
            )

        statList = [ 
            self.statistics[idx][0] for idx in indexList
        ] if indexList != [] else [
            i[0] for i in self.statistics
        ]

        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
        progress_step = 100.0 / featCount if featCount else 0

        fields = inputLyr.fields()
        for stat in statList:
            fields.append(
                QgsField(stat, QVariant.Double)
            )

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

        vector_utils = VectorUtils()

        for current_feat, feat in enumerate(features):
            if feedback is not None and feedback.isCanceled():
                break
            newFeat = vector_utils.calculateStatistics(
                feat,
                statList,
                fields
            )
            sink.addFeature(
                newFeat,
                QgsFeatureSink.FastInsert
            )
            # self.current_feat += 1
            if feedback is not None:
                feedback.setProgress(
                    current_feat * progress_step
                )
        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 'Find polygon statistics'

    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 'Dataset Statistics'

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

    def createInstance(self):
        return FindPolygonStatisticsAlgorithm()
