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

"""
/***************************************************************************
 AgredateAdmbyMesh
                                 A QGIS plugin
 Read a CSV file and calculate the number of lines for each item in the specified column
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2020-05-15
        copyright            : (C) 2020 by Yoichi Kayama
        email                : yoichi.kayama@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.                                   *
 *                                                                         *
 ***************************************************************************/
"""

__author__ = 'Yoichi Kayama'
__date__ = '2021-2-6'
__copyright__ = '(C) 2021 by Yoichi Kayama'

# 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 (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingException,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterEnum,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsProcessingParameterVectorDestination,
                       QgsProcessingParameterFile,
                       QgsProcessingParameterVectorLayer,
                       QgsProcessingParameterBoolean,
                       QgsProcessingParameterField,
                       QgsProcessingParameterNumber,
                       QgsProcessingOutputVectorLayer,
                       QgsVirtualLayerDefinition,
                       QgsVectorLayer,
                       QgsProcessingUtils,
                       QgsProcessingMultiStepFeedback,
                       QgsProject,
                       QgsWkbTypes,
                       QgsExpression,
                       QgsField,
                       QgsFields,
                       QgsFeature,
                       QgsFeatureRequest,
                       QgsProcessingParameterString)


import processing
import sqlite3
import csv

from .mod import  agtools

class AggregatePopMeshbyMeshAlgorithm(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.

    OUTPUT = 'OUTPUT'
    INPUT = 'INPUT'

    #ENCODING = 'ENCODING'

    #encode = ['SJIS','UTF-8']

    #proportional_div = ['人口','面積']


    def initAlgorithm(self, config):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """
        self.addParameter(
            QgsProcessingParameterVectorLayer(
                self.INPUT,
                '入力人口×行政界UNIONレイヤ'
            )
         )


                #　　ポリゴン面積フィールド
        self.addParameter(QgsProcessingParameterField('pareafield', 'ポリゴン面積フィールド', 
                         type=QgsProcessingParameterField.Numeric, parentLayerParameterName=self.INPUT, optional=False, allowMultiple=False, defaultValue=None))

        #   ポリゴン集計値フィールド
        self.addParameter(QgsProcessingParameterField('polsmpl', 'ポリゴン集計値フィールド', 
                         type=QgsProcessingParameterField.Numeric, parentLayerParameterName=self.INPUT, optional=False, allowMultiple=False))


        

        self.addParameter(QgsProcessingParameterVectorLayer('meshlayer', 'メッシュレイヤ',
                         types=[QgsProcessing.TypeVectorPolygon], defaultValue=None))

        self.addParameter(QgsProcessingParameterField('meshid', 'メッシュIDフィールド', 
                         type=QgsProcessingParameterField.String, parentLayerParameterName='meshlayer', optional=False, allowMultiple=False))




        # 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).
        self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.OUTPUT,
                '出力レイヤ'
            )
        )

    def processAlgorithm(self, parameters, context, model_feedback):
        """
        Here is where the processing itself takes place.
        """
        results = {}

        feedback = QgsProcessingMultiStepFeedback(7, model_feedback)

        inputLayer = self.parameterAsVectorLayer(
            parameters,
            self.INPUT,
            context
        )
        if inputLayer  is None:
            raise QgsProcessingException(self.tr('input layer missed'))



        meshLayer = self.parameterAsVectorLayer(
            parameters,
            "meshlayer",
            context
        )
        if meshLayer  is None:
            raise QgsProcessingException(self.tr('mesh layer missed'))

        meshidfields = self.parameterAsFields  (
             parameters,
             'meshid',
             context
        )


        pareafields = self.parameterAsFields  (
             parameters,
             'pareafield',
             context
        )

        
        psamplefields = self.parameterAsFields  (
             parameters,
             'polsmpl',
             context
        )




      

        feedback.setCurrentStep(1)
        if feedback.isCanceled():
            return {}

        #  union
 


#   集計用メッシュと人口×行政界メッシュの　UNIONを作成する

        params2 = { 'INPUT' :  meshLayer , 'INPUT_FIELDS' : [], 
                'OUTPUT' : QgsProcessing.TEMPORARY_OUTPUT, 
                # 'OUTPUT' : parameters["OUTPUT"], 
                'OVERLAY' : inputLayer, 'OVERLAY_FIELDS' : [] }
                 #             'OUTPUT' : parameters["OUTPUT"], 'OVERLAY' : res3["OUTPUT"], 'OVERLAY_FIELDS' : [] }

#      ここはIntersectではなくて union
        #res2 = processing.run('native:intersection', params2,  context=context, feedback=feedback ,is_child_algorithm=True)
        res2 = processing.run('qgis:union', params2,  context=context, feedback=feedback ,is_child_algorithm=True)
        if feedback.isCanceled():
            return {}

        feedback.pushConsoleInfo( "union  OK "  )



   #  作成UNIONのポリゴン面積算出

   #  面積出力フィールド名

        feedback.setCurrentStep(2)

        darea_column = 'divu_area'

        params3 = { 'INPUT' :  res2["OUTPUT"], 'FIELD_NAME' : darea_column , 'FIELD_TYPE': 0, 'FIELD_LENGTH':12, 'FIELD_PRECISION':5, 
                 'NEW_FIELD':1,'FORMULA':'$area','OUTPUT' :QgsProcessing.TEMPORARY_OUTPUT }

        res3 = processing.run('qgis:fieldcalculator', params3, context=context, feedback=feedback ,is_child_algorithm=True)

        if feedback.isCanceled():
            return {}

        feedback.pushConsoleInfo( "caluculate area of union polygon OK "  )


   #　　作成UNIONと元 UNIONの面積比率
        feedback.setCurrentStep(3)

        newFlag = True
        ratio_column = 'divu_ratio'
        ratio_str = darea_column + "/" + pareafields[0]
        params4 = { 'INPUT' : res3["OUTPUT"], 'FIELD_NAME' :  ratio_column , 'FIELD_TYPE': 0, 'FIELD_LENGTH':12, 
         #            'FIELD_PRECISION':5, 'NEW_FIELD':newFlag,'FORMULA':ratio_str,'OUTPUT' :parameters["OUTPUT"] }
                    'FIELD_PRECISION':5, 'NEW_FIELD':newFlag,'FORMULA':ratio_str,'OUTPUT' :QgsProcessing.TEMPORARY_OUTPUT } 

        res4 = processing.run('qgis:fieldcalculator', params4,  context=context, feedback=feedback ,is_child_algorithm=True)
        if feedback.isCanceled():
            return {}
        feedback.pushConsoleInfo( "calc ratio ok " )




   #　　元UNIONの想定集計値に面積比率をかけて作成UNIONの想定調査値を算出する
        feedback.setCurrentStep(4)

        sv_column = 'snum_nv'
        sv_str =  psamplefields[0] + "*"  + ratio_column 

        feedback.pushConsoleInfo( "expres  " + sv_str)
        params5 = { 'INPUT' : res4["OUTPUT"], 'FIELD_NAME' :  sv_column , 'FIELD_TYPE': 0, 'FIELD_LENGTH':12, 
         #            'FIELD_PRECISION':5, 'NEW_FIELD':newFlag,'FORMULA':sv_str,'OUTPUT' :parameters["OUTPUT"] }
                    'FIELD_PRECISION':5, 'NEW_FIELD':newFlag,'FORMULA':sv_str,'OUTPUT' :QgsProcessing.TEMPORARY_OUTPUT } 

        res5 = processing.run('qgis:fieldcalculator', params5,  context=context, feedback=feedback ,is_child_algorithm=True)
        if feedback.isCanceled():
            return {}
        feedback.pushConsoleInfo( "calc ratio2 ok " )





   #　　作成UNIONの想定調査値をメッシュ別に集計する



    #   按分数値をもとにメッシュ別集計
        feedback.setCurrentStep(5)
        meshid_f = meshidfields[0]


        alg_paramsg_n = {
                           'LAYERS': res5["OUTPUT"],
                           'OVERWRITE': False,
                          'SAVE_STYLES': False,
                           'OUTPUT': QgsProcessing.TEMPORARY_OUTPUT
                           }
        lout  = processing.run('native:package', alg_paramsg_n, context=context, feedback=feedback, is_child_algorithm=True)  



        agar = []


        tgLayer = lout["OUTPUT"]

   

        if type(tgLayer) is str:
            tgLayer =  QgsVectorLayer(tgLayer, "intesect", "ogr")


        

        for field in tgLayer.fields():

            agreg = {}

            agreg['input'] = '"' + field.name() + '"'


            #feedback.pushConsoleInfo( "name "  + field.name() )
            agreg['name']  = field.name()
            agreg['aggregate'] = 'first_value'

            agreg['length'] =field.length()
            agreg['precision'] =field.precision()     
            agreg['type'] =field.type()   

            if field.name() == sv_column :
                 agreg['aggregate'] = 'sum'

                 agar.append(agreg)

            if field.name() == meshid_f :
                 agar.append(agreg)

        
        params6 = { 'INPUT' : res5["OUTPUT"], 'GROUP_BY' : meshid_f, 'AGGREGATES': agar, 
         #               'OUTPUT' :parameters["OUTPUT"]  }
                       'OUTPUT' :QgsProcessing.TEMPORARY_OUTPUT }

        feedback.pushConsoleInfo( "aggregate "  )
        res6 = processing.run('qgis:aggregate', params6,  context=context, feedback=feedback ,is_child_algorithm=True)

        if feedback.isCanceled():
            return {}
        feedback.pushConsoleInfo( "aggregate OK "  )



    #   レイヤ結合　　qgis:joinattributestable
        #QgsProject.instance().addMapLayer(res7["OUTPUT"])

        feedback.setCurrentStep(6)

        param7 = { 'DISCARD_NONMATCHING' : False, 'FIELD' : meshid_f, 'FIELDS_TO_COPY' : [sv_column], 'FIELD_2' : meshid_f, 
             'INPUT' : meshLayer, 
             'INPUT_2' : res6['OUTPUT'], 'METHOD' : 1, 'OUTPUT' : QgsProcessing.TEMPORARY_OUTPUT, 'PREFIX' : '' }



        res7 = processing.run('qgis:joinattributestable', param7,  context=context, feedback=feedback ,is_child_algorithm=True)

        if feedback.isCanceled():
            return {}
        feedback.pushConsoleInfo( "joinattributetable OK"  )


    #   結果フィールド名変更
        feedback.setCurrentStep(7)

        param8 = { 'FIELD' : sv_column , 
           'INPUT' : res7["OUTPUT"], 'NEW_NAME' : 'snum', 'OUTPUT' : parameters["OUTPUT"] }

      
        res8 = processing.run('qgis:renametablefield', param8,  context=context, feedback=feedback ,is_child_algorithm=True)

        if feedback.isCanceled():
            return {}
        feedback.pushConsoleInfo( "field rename OK"  )          



        results["OUTPUT"] = res8["OUTPUT"]
       # results["LIMITPOL"] = matches

        return  results


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

    def displayName(self):
        """
        Returns the translated algorithm name, which should be used for any
        user-visible display of the algorithm name.
        """
        return '行政界×人口メッシュ メッシュ集計（単一メッシュ)'

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

    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 self.tr('Aggregate')

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

    def createInstance(self):
        return AggregatePopMeshbyMeshAlgorithm()
