# -*- coding: utf-8 -*-
import io


"""
/***************************************************************************
 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,
                       QgsProcessingParameterEnum,
                       QgsProcessingParameterBoolean,
                       QgsProcessingParameterString,
                       QgsProcessingParameterExtent,
                       QgsProcessingParameterField,
                       QgsProcessingParameterExpression,
                       QgsProcessingParameterFileDestination,
                       QgsProcessingParameterVectorLayer,
                       QgsProcessingParameterFileDestination,
                       QgsProcessingParameterFile)
import codecs

class MusliwParam(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.
    
    CTC = 'CTC'
    CATT ='CATT'
    CMAP='CMAP'
    CBOA='CBOA'
    CTMAP='CTMAP'
    TBOA_MIN='TBOA_MIN'
    TBOA_MAX='TBOA_MAX'
    NBJOURS='NBJOURS'
    PEAGE='PEAGE'
    COUT_MAX='COUT_MAX'
    TMAP_MAX='TMAP_MAX'
    TOLL='TOLL'
    SORTIE_CHEMINS='SORTIE_CHEMINS'
    TEMPS_DETAILLES='TEMPS_DETAILLES'
    FILTRE='FILTRE'
    DEMI_TOURS_INTERDITS='DEMI_TOURS_INTERDITS'
    SORTIE_SERVICES='SORTIE_SERVICES'
    SORTIE_TRANSFERTS='SORTIE_TRANSFERTS'
    SORTIE_NOEUDS='SORTIE_NOEUDS'
    ECHELLE='ECHELLE'
    PU='PU'
    MAX_CLASSES='MAX_CLASSES'
    SORTIE='SORTIE'
    OUTPUT_STOPS='OUTPUT_STOPS'


    def initAlgorithm(self, config):
        """
        Here we define the inputs and output of the algorithm, along
        with some other properties.
        """
        
        self.addParameter(
            QgsProcessingParameterString(
                self.CTC,
                self.tr('In vehicle weight'),
                '1'
                
            )
        )
        self.addParameter(
            QgsProcessingParameterString(
                self.CATT,
                self.tr('Waiting weight'),
                '1'
            )
        )
        self.addParameter(
            QgsProcessingParameterString(
                self.CMAP,
                self.tr('Individual modes weight'),
                '1.5'
            )
        )

        self.addParameter(
            QgsProcessingParameterString(
                self.CBOA,
                self.tr('Boarding weight'),
                '3'
            )
        )
        self.addParameter(
            QgsProcessingParameterString(
                self.CTMAP,
                self.tr('Individual mode speed factor'),
                '1'
            )
        )        
        self.addParameter(
            QgsProcessingParameterString(
                self.TBOA_MIN,
                self.tr('Minimum transfer delay'),
                '2'
            )
        ) 
        self.addParameter(
            QgsProcessingParameterString(
                self.TBOA_MAX,
                self.tr('Maximum transfer delay'),
                '60'
            )
        )      
        self.addParameter(
            QgsProcessingParameterNumber(
                self.NBJOURS,
                self.tr('Extra day duration'),
                type=QgsProcessingParameterNumber.Integer,
                defaultValue=0
               
            )
        )   
        self.addParameter(
            QgsProcessingParameterNumber(
                self.TMAP_MAX,
                self.tr('Max. individual time budget'),
                type=QgsProcessingParameterNumber.Double,
                defaultValue=60.0
               
            )
        )           
        self.addParameter(
            QgsProcessingParameterNumber(
                self.COUT_MAX,
                self.tr('Maximum generalized time'),
                type=QgsProcessingParameterNumber.Double,
                defaultValue=1500.0
               
            )
        )   
        self.addParameter(
            QgsProcessingParameterString(
                self.TOLL,
                self.tr('Toll weight'),
                '0'
            )
        )          
        self.addParameter(
            QgsProcessingParameterString(
                self.FILTRE,
                self.tr('Output filter'),
                optional=True
            )
        )  
        self.addParameter(
            QgsProcessingParameterEnum(
                self.TEMPS_DETAILLES,
                self.tr('Output links times?'),
                [self.tr('No output'),self.tr('Without timetable links'),self.tr("With timetable links"),self.tr("Compact mode")],
                defaultValue=0
            )
        ) 
        self.addParameter(
            QgsProcessingParameterBoolean(
                self.DEMI_TOURS_INTERDITS,
                self.tr('Prohibited U-turns?'),
                True
            )
        )
        self.addParameter(
            QgsProcessingParameterBoolean(
                self.SORTIE_CHEMINS,
                self.tr('Output paths?'),
                True
            )
        )

        self.addParameter(
            QgsProcessingParameterBoolean(
                self.SORTIE_SERVICES,
                self.tr('Output services?'),
                False
            )
        ) 
        self.addParameter(
            QgsProcessingParameterBoolean(
                self.SORTIE_TRANSFERTS,
                self.tr('Output transfers?'),
                False
            )
        ) 
        self.addParameter(
            QgsProcessingParameterBoolean(
                self.SORTIE_NOEUDS,
                self.tr('Output node times?'),
                False
            )
        )
        self.addParameter(
            QgsProcessingParameterBoolean(
                self.OUTPUT_STOPS,
                self.tr('Output stops?'),
                False
            )
        )        
        
        self.addParameter(
            QgsProcessingParameterNumber(
                self.ECHELLE,
                self.tr('Algorithm scale?'),
                type=QgsProcessingParameterNumber.Integer,
                defaultValue=20
               
            )
        )   
        self.addParameter(
            QgsProcessingParameterNumber(
                self.PU,
                self.tr('Algorithm exponent?'),
                type=QgsProcessingParameterNumber.Integer,
                defaultValue=2
               
            )
        )     
        self.addParameter(
            QgsProcessingParameterNumber(
                self.MAX_CLASSES,
                self.tr('nb classes?'),
                type=QgsProcessingParameterNumber.Integer,
                defaultValue=10000
               
            )
        )           
        self.addParameter(
            QgsProcessingParameterFileDestination(
                self.SORTIE,
                self.tr('Parameters file'),
                "*.txt"
                
            )
        )
        


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

        ctc = self.parameterAsString(parameters, self.CTC, context)
        catt = self.parameterAsString(parameters, self.CATT, context)
        cmap = self.parameterAsString(parameters, self.CMAP, context)
        cboa = self.parameterAsString(parameters, self.CBOA, context)
        ctmap = self.parameterAsString(parameters, self.CTMAP, context)
        tboa_min = self.parameterAsString(parameters, self.TBOA_MIN, context)
        tboa_max = self.parameterAsString(parameters, self.TBOA_MAX, context)
        toll = self.parameterAsString(parameters, self.TOLL, context)
        nb_jours=self.parameterAsInt(parameters, self.NBJOURS, context)
        filtre = self.parameterAsString(parameters, self.FILTRE, context)
        demi_tours=self.parameterAsBool(parameters, self.DEMI_TOURS_INTERDITS, context)
        sortie_transferts = self.parameterAsFile(parameters, self.SORTIE_TRANSFERTS, context)
        sortie_chemins=self.parameterAsString(parameters, self.SORTIE_CHEMINS, context)
        sortie_services=self.parameterAsString(parameters, self.SORTIE_SERVICES, context)
        sortie_noeuds=self.parameterAsString(parameters, self.SORTIE_NOEUDS, context)
        sortie_stops=self.parameterAsBool(parameters, self.OUTPUT_STOPS, context)
        temps_detailles=self.parameterAsEnum(parameters, self.TEMPS_DETAILLES, context)
        echelle=self.parameterAsInt(parameters, self.ECHELLE, context)
        pu=self.parameterAsInt(parameters, self.PU, context)
        tmap_max=self.parameterAsDouble(parameters, self.TMAP_MAX, context)
        cout_max=self.parameterAsDouble(parameters, self.COUT_MAX, context)
        nb_classes=self.parameterAsInt(parameters, self.MAX_CLASSES, context)
        sortie=self.parameterAsFileOutput(parameters, self.SORTIE, context)

        if sortie_stops==True:
            temps_detailles=temps_detailles+10
        
        fich_param=io.open(sortie,"w",encoding="utf-8")
        fich_param.write('0'+self.tr(';algorithm')+'\n')
        fich_param.write(unicode(demi_tours).title()+self.tr(";prohibited U-turns")+"\n")
        fich_param.write(unicode(nb_classes)+self.tr(";max buckets")+"\n")
        fich_param.write(unicode(nb_jours)+self.tr(";number of days")+"\n")
        fich_param.write(self.tr(";matrix file")+"\n")
        fich_param.write(self.tr(";turns and transfers files")+"\n")
        fich_param.write(self.tr(";network file")+"\n")
        fich_param.write(self.tr(";generic output file")+"\n")
        fich_param.write(unicode(echelle)+self.tr(";algorithm parameter")+"\n")
        fich_param.write(unicode(pu)+self.tr(";algorithm power")+"\n")
        fich_param.write(unicode(sortie_chemins).title()+self.tr(";output paths")+"\n")
        fich_param.write(unicode(sortie_services).title()+self.tr(";output services")+"\n")
        fich_param.write(unicode(temps_detailles)+self.tr(";output travel times")+"\n")
        fich_param.write(unicode(sortie_transferts).title()+self.tr(";output turns and transfers")+"\n")
        fich_param.write(cboa+self.tr(";boarding weight")+"\n")
        fich_param.write(cmap+self.tr(";individual mode weight")+"\n")
        fich_param.write(ctmap+self.tr(";individual travel time factor")+"\n")
        fich_param.write(ctc+self.tr(";in-vehicle time weight")+"\n")
        fich_param.write(catt+self.tr(";wait time weight")+"\n")
        fich_param.write(tboa_min+self.tr(";min transfer time")+"\n")
        fich_param.write(tboa_max+self.tr(";max transfer time")+"\n")
        fich_param.write(unicode(tmap_max)+self.tr(";max individual travel time")+"\n")
        fich_param.write(toll+self.tr(";toll weight")+"\n")
        fich_param.write(filtre+self.tr(";output types filter")+"\n")
        fich_param.write(unicode(cout_max)+self.tr(";max travel cost")+"\n")
        fich_param.write(unicode(sortie_noeuds).title()+self.tr(";output nodes")+"\n")
        fich_param.write("False"+self.tr(";output isolated links")+"\n")
        fich_param.close()
        

        return {'parameters': sortie}


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

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

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

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

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

    def shortHelpString(self):
        return self.tr("""
        Create a set of parameters usefull for multimodal routing or acceesibility computation with Musliw
        Produce a parameter file (to be selected in musliw computation):
        
        Parameters:
            In vehicle weight : weight factor for travel time in vehicle (time baseds mode e.g bus, tram, train, metro, airplane, ferry,...)
            Waiting weight: weight factor for waiting time
            Individual mode weight : weight factor for individual modes travel times (e.g car, walking, cycling, ...)
            Boarding weight: weight factor for boarding time
            Individual mode speed factor: homothetic factor that apply to the individual travel times
            Minimum transfer delay : minimum safety time for transfer (ex: 5 means that you should wait at least 5 minutes at a stop before the bus leaves
            Maximum transfer delay: maximum waiting time for transfer (ex: 60 means that you will not be able to take atrain that leaves more that 60 minutes after you arrive)
            Extra day duration: By default Musliw takes only into account timetable of the day selected in the matrix. If you can extend with the timetable of the day after (if departure) or the day before (arrival) your must enter 1
            Max. indiviudal time budegt: The algorithm path will not explore shortest paths that have a individual time budget greater than this value
            Maximum generalized time: The algorithm path will not explore shortest paths that have a total generalised cost greater than this value
            Toll weight: weight factor for toll attribute
            Output filter: specify the type of links you want in the reports (empty will output all links ex: metro|bus|tram will export only metro , bus and tram lines
            Output links times: select what you want detailed output at link level (No, without ou with timetable based links)
            Prohibited U-turns: choose if if you want to allow u-turns in shortest paths computation
            Output paths: Check if you want to output detailed paths
            Output services: Check if you want to have detailed outputs for each service
            Output transfers: Check if you want to have detailed outputs on turns and transfers
            Outpout nodes times: Check if you want to have detailed outputs at node level
            Algorithm scale: Parameter of the shortest path algorithm
            Algorithm exponent: The algorithm parameter exponent
            Nb classes: The number of buckets of the shortest path algorithm
            Parameter file: The output parameter file to be used in musliw computation
            
            
        """)

    def createInstance(self):
        return MusliwParam()
