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

"""
/***************************************************************************
 Networks
                                 A QGIS plugin
 Networks
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2018-02-26
        copyright            : (C) 2018 by Patrick Palmier
        email                : patrick.palmier@cerema.fr
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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__ = 'Patrick Palmier'
__date__ = '2018-02-26'
__copyright__ = '(C) 2018 by Patrick Palmier'

# 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 *
from qgis.utils import *
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsProcessingParameterNumber,
                       QgsProcessingParameterBoolean,
                       QgsProcessingParameterString,
                       QgsProcessingParameterExtent,
                       QgsProcessingParameterField,
                       QgsProcessingParameterExpression,
                       QgsProcessingParameterFileDestination)
import io
import statistics
import pandas
import numpy
import gc

class PathIndicators(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'
    TATT1='TATT1'
    TCSEUL='TCSEUL'
    TRANSFER_MAX='TRANSFER_MAX'
    FICHIER_RESULTAT='FICHIER_RESULTAT'


    


    def initAlgorithm(self, config):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """
       
        self.addParameter(
            QgsProcessingParameterFile(
                self.INPUT,
                self.tr('Path output file'),
                QgsProcessingParameterFile.File,
                "txt"

            )
        )
        



        
        self.addParameter(
            QgsProcessingParameterBoolean(
                self.TATT1,
                self.tr('Remove initial/final waiting time?'),
                True
                
            )
        )
        self.addParameter(
            QgsProcessingParameterBoolean(
                self.TCSEUL,
                self.tr('Time based links only?'),
                True
                
            )
        )

        
        self.addParameter(
            QgsProcessingParameterFileDestination(
                self.FICHIER_RESULTAT,
                self.tr('Path indicators file'),
                "*.txt"
                
            )
        )

        # 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).


    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.
        fichier_chemins=self.parameterAsFile(parameters,self.INPUT,context)
        temps_attente_terminal=self.parameterAsBool(parameters, self.TATT1, context)
        tc_seul= self.parameterAsBool(parameters, self.TCSEUL, context)
        fichier_resultat=self.parameterAsFileOutput(parameters,self.FICHIER_RESULTAT,context)

        dec=lambda x: float(x.replace(',','.'))
        chemins=pandas.read_csv(fichier_chemins,sep=';',decimal='.',converters={'tatt':dec,'tatt1':dec,'temps':dec,'tmap':dec,'tveh':dec,'cout':dec,
                'heureo':dec,'heured':dec,'jour':dec,'tcorr':dec,'ncorr':dec,'longueur':dec,'volau':dec,'boai':dec,'alij':dec,'toll':dec})
        if temps_attente_terminal==True:
            chemins.eval('twait=tatt-tatt1',inplace=True)
        else:
            chemins['twait']=chemins['tatt']
        ch=chemins.groupby('id')
        sortie=open(fichier_resultat,"w")
        sortie.write('id;temps;temps_individuel;temps_attente;temps_TC;longueur;voyages;montee;descente;temps_individuel1;longueur1;temps_individuel2;longueur2\n')
        nb=len(ch)
        for u,(k,i) in enumerate(ch):
            i['temps_i']=i['tmap'].diff(periods=-1).fillna(0)
            i['l']=i['longueur'].diff(periods=-1).fillna(0)
            i['temps_att']=i['twait'].diff(periods=-1).fillna(0)
            i['temps_veh']=i['tveh'].diff(periods=-1).fillna(0)
            
            i.eval("voyages=1*(boai>0)",inplace=True)
            texte_montee='||'.join(i.query('boai>0')['type'].str.cat(i['texte'],sep='-'))
            texte_descente='||'.join(i.query('alij>0')['type'].str.cat(i['texte'],sep='-'))
            temps=i['temps'].max()
            temps_individuel=i['temps_i'].sum()
            temps_attente=i['temps_att'].sum()
            temps_TC=i['temps_veh'].sum()
            longueur=i['l'].sum()
            voyages=i['voyages'].sum()
            ma_liste=i.query('ligne>0').index.tolist()

            if len(ma_liste)>0:
                min_ligne=min(ma_liste)
                ti1=i.loc[:min_ligne-1]['temps_i'].sum()
                l1=i.loc[:min_ligne-1]['l'].sum()
                
                max_ligne=max(ma_liste)
                ti2=i.loc[max_ligne+2:]['temps_i'].sum()
                l2=i.loc[max_ligne+2:]['l'].sum()
            else:
                ti1=0
                l1=0
                ti2=0
                l2=0
            resultat=[k,temps,temps_individuel,temps_attente,temps_TC,longueur,voyages,texte_montee,texte_descente,ti1,l1,ti2,l2]
            if tc_seul==False or (tc_seul==True and voyages>0):
                feedback.setProgress(u*100/nb)
                sortie.write(";".join([str(k) for k in resultat])+"\n")
        sortie.close()
        gc.collect()
        return {self.FICHIER_RESULTAT: fichier_resultat}


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

    def displayName(self):
        """
        Returns the translated algorithm name, which should be used for any
        user-visible display of the algorithm name.
        """
        return self.tr('indicators by path')

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

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

    def tr(self, string):
        return QCoreApplication.translate('PathIndicators', string)
        
    def shortHelpString(self):
        return self.tr("""
        Produce indicators aggregated by OD. This analysis is usefull when you want to study the variation of travel times during a time period
		
        Parameters:
            path ouput file: the Musliw detailed path output file (<FILENAME>_od.txt)
            remove initial/final boarding time: If checked the initial or final waiting time (between the excepted arrival or departure time
            and the real one is substracted from the total travel time
			time based links only: If checked only time based links are analysed
            path indicator file: name of the result file (delimited text with ";" as separator) which contains the following attributes 
            id: OD id
            temps: total travel time
            temps individuel: individual modes travel time
            temps_attente: waiting time
            temps_TC: timetable travel time
            longueur: length
            voyages: number of boardings
            montee: initial timetable modes text
            descente: final timetable modes text
            temps_individuel1: initial incoming travel time
            longueur1: intinial incoming length
            temps_individuel2: final outgoing travel time
            longueur2: final outgoing length
            
            
        """)

    def createInstance(self):
        return PathIndicators()
