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

"""
/***************************************************************************
 LightPollutionToolbox
                                 A QGIS plugin
 Light pollution indicators (focus on public lighting)
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2020-04-20
        copyright            : (C) 2020 by Mathieu Chailloux
        email                : mathieu@chailloux.org
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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__ = 'Mathieu Chailloux'
__date__ = '2020-04-20'
__copyright__ = '(C) 2020 by Mathieu Chailloux'

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

__revision__ = '$Format:%H$'

from PyQt5.QtCore import QCoreApplication, QVariant
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsFeatureRequest,
                       QgsFeature,
                       QgsProject,
                       QgsVectorLayer,
                       QgsGraduatedSymbolRenderer,
                       QgsProcessingUtils,
                       QgsProcessingContext,
                       QgsProcessingMultiStepFeedback,
                       QgsProcessingException,
                       QgsProcessingAlgorithm,
                       QgsProcessingFeatureSourceDefinition,
                       QgsProcessingParameterDefinition,
                       QgsProcessingParameterBoolean,
                       QgsProcessingParameterField,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsProcessingParameterNumber,
                       QgsProcessingParameterEnum,
                       QgsProcessingParameterExpression,
                       QgsProcessingParameterMultipleLayers,
                       QgsProcessingParameterVectorDestination,
                       QgsFields,
                       QgsField)

from ..qgis_lib_mc import qgsUtils, styles                       

   
class ClassifyLightingAlg(qgsUtils.BaseProcessingAlgorithm):
    
    ALG_NAME = 'classifyLighting'

    INPUT = 'INPUT'
    FIELD = 'FIELD'
    CLASSIF_MODE = 'CLASSIF_MODE'
    OUTPUT = 'OUTPUT'
        
    def displayName(self):
        return self.tr('Classify lighting layer')
    
    def initAlgorithm(self, config=None):
        self.classif_modes = [
            self.tr('Flux'),
            self.tr('Color Temperature'),
            self.tr('ULR'),
        ]
        self.addParameter(
            QgsProcessingParameterFeatureSource(
                self.INPUT,
                self.tr('Lighting layer'),
                [QgsProcessing.TypeVectorPoint]))
        self.addParameter(
            QgsProcessingParameterField(
                self.FIELD,
                description=self.tr('Field to classify'),
                defaultValue='flux',
                type=QgsProcessingParameterField.Numeric,
                parentLayerParameterName=self.INPUT))
        self.addParameter(
            QgsProcessingParameterEnum(
                self.CLASSIF_MODE,
                self.tr('Classification mode'),
                options=self.classif_modes,
                defaultValue=0))
        #self.initAlgFromFieldInfo(self.tr('ULR field'),suffix='_ulr')
    
    def processAlgorithm(self, parameters, context, feedback):
        self.in_layer = self.parameterAsVectorLayer(parameters,self.INPUT,context)
        self.field = self.parameterAsString(parameters,self.FIELD,context)
        self.mode = self.parameterAsEnum(parameters,self.CLASSIF_MODE,context)
        if not self.in_layer:
            raise QgsProcessingException("No input layer")
        if self.mode == 0:
            suffix = '_flux'
        elif self.mode == 1:
            suffix = '_tempCoul'
        elif self.mode == 2:
            suffix = '__ulr'
        else:
            raise QgsProcessingException("Unexpected classification mode : " + str(self.mode))
        self.clone = QgsVectorLayer(self.in_layer.source(),
            self.in_layer.name() + suffix, self.in_layer.providerType())
        return { self.OUTPUT : self.clone }
        
    def postProcessAlgorithm(self,context,feedback):
        if not self.clone:
            raise QgsProcessingException("No duplicate layer")
        if self.mode == 0:
            self.classifyFlux()
        elif self.mode == 1:
            self.classifyTempCoul()
        elif self.mode == 2:
            self.classifyULR()
        else:
            assert(False)
        QgsProject.instance().addMapLayer(self.clone, addToLegend=True)
        return { self.OUTPUT : self.clone }
        
    def classifyFlux(self):
        color_ramp = styles.mkColorRamp('Plasma')
        classif_method = QgsGraduatedSymbolRenderer.Quantile
        #classif_method = QgsGraduatedSymbolRenderer.Jenks
        renderer = styles.mkGraduatedRenderer(self.clone,self.field,color_ramp,
            nb_classes=5,classif_method=classif_method)
        styles.setRenderer(self.clone,renderer)
        
    def classifyTempCoul(self):
        class_bounds = [2000,2400,2700,3000]
        color_ramp = styles.mkColorRamp('RdYlBu')
        styles.setCustomClasses2(self.clone,self.field,color_ramp,class_bounds)
        
    def classifyULR(self):
        class_bounds = [1,4]
        color_ramp = styles.getGradientColorRampRdYlGn()
        styles.setCustomClasses2(self.clone,self.field,color_ramp,class_bounds)
        
    def shortHelpString(self):
        helpStr = "Classify lighting layer according to selected mode (flux, color temperature, ULR)"
        return self.tr(helpStr)
