# -*- 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,QDate,QDateTime,QTime
from qgis.core import *
from qgis.utils import *
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsProcessingParameterNumber,
                       QgsProcessingParameterBoolean,
                       QgsProcessingParameterString,
                       QgsProcessingParameterExtent,
                       QgsProcessingParameterField,
                       QgsProcessingParameterExpression,
                       QgsProcessingParameterFileDestination,
                       QgsSpatialIndex,
                       QgsGeometry,
                       QgsFeature,
                       QgsCoordinateTransform,
                       QgsCoordinateReferenceSystem
                       )
import io
import datetime,re, gc

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

    REP_SOURCE = 'REP_SOURCE'
    REP_RESULTAT='REP_RESULTAT'
    PREFIXE_RESEAU = 'PREFIXE_RESEAU'
    UIC = 'UIC'
    SPLIT_FORMULA = 'SPLIT_FORMULA'
    ENCODE='ENCODE'

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

        self.addParameter(
            QgsProcessingParameterFile(
                self.REP_SOURCE,
                self.tr('GTFS source folder '),
                QgsProcessingParameterFile.Folder
                
            )
        )
        self.addParameter(
            QgsProcessingParameterFolderDestination(
                self.REP_RESULTAT,
                self.tr('GTFS output folder')
                
                
            )
        )
        self.addParameter(
            QgsProcessingParameterString(
                self.PREFIXE_RESEAU,
                self.tr('Network Id')
                
            )
        )
        self.addParameter(
            QgsProcessingParameterBoolean(
                self.UIC,
                self.tr('Extract stop_id?'),
                False
            )
        )
        self.addParameter(
            QgsProcessingParameterString(
                self.SPLIT_FORMULA,
                self.tr('Extract formula'),
                "[-8:]"
            )
        )
        self.addParameter(
            QgsProcessingParameterString(
                self.ENCODE,
                self.tr('Encoding'),
                "utf_8_sig"
            )
        )        

        # 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.
        rep_source = self.parameterAsFile(parameters, self.REP_SOURCE, context)
        rep_resultat=self.parameterAsFileOutput(parameters, self.REP_RESULTAT, context)
        prefixe_reseau=self.parameterAsString(parameters,self.PREFIXE_RESEAU,context)
        uic=self.parameterAsBool(parameters,self.UIC,context)
        split_formula=self.parameterAsString(parameters,self.SPLIT_FORMULA,context)
        encodage=self.parameterAsString(parameters,self.ENCODE,context)
        
        #print(rep_resultat,self.REP_RESULTAT)
        if os.path.split(rep_resultat)[1]==self.REP_RESULTAT:
            rep_resultat=os.path.split(rep_resultat)[0]
        self.importGTFS(rep_source,rep_resultat,prefixe_reseau,uic,split_formula,encodage)
        gc.collect()

        return {self.REP_SOURCE: self.REP_RESULTAT}

        
    def importGTFS(self,rep,sortie,prefixe,uic,formula,encodage):
        arrets={}
        stops=io.open(rep+"/stops.txt","r",encoding=encodage)
        iparent=-1
        for i,ligne in enumerate(stops):
            try:
                test=ligne.startswith(codecs.BOM_UTF8)
                if test:
                    ligne=ligne[3:]
            except:
                pass
            ligne=(ligne.replace("\n","")).replace("\r","")
            elements= re.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)",ligne)
            #elements=ligne.strip().split(',')
            for z,e in enumerate(elements):
                elements[z]=e.strip('"').strip()

            if len(elements)>1:
                if i>0:
                    if uic==True:
                        elements[iid]=eval("prefixe+elements[iid]"+formula)
                    else:
                        elements[iid]=prefixe+elements[iid].strip("\"")
                    
                    elements[idx]=elements[idx].strip().strip("\"")
                    
                    if iparent>=0 and elements[iparent] not in ['',None]:
                        elements[iparent]=prefixe+elements[iparent].strip("\"")
                    arrets[elements[iid]]=elements
                else:
                    for i1,i2 in enumerate(elements):
                        elements[i1]=i2.strip("\"").strip()
                    idx=elements.index('stop_lon')
                    idy=elements.index('stop_lat')
                    iid=elements.index('stop_id')
                    iname=elements.index('stop_name')
                    if "parent_station" in elements:
                        iparent=elements.index('parent_station')
                    if "stop_desc" in elements:
                        idesc=elements.index('stop_desc')
                    hstops=ligne
        stops.close()
                         
                         
        lignes={}
        routes=io.open(rep+'/routes.txt','r',encoding=encodage)
        test_agency='ZZ'
        for i,ligne in enumerate(routes):
            try:
                test=ligne.startswith(codecs.BOM_UTF8)
                if test:
                    ligne=ligne[3:]
            except:
                pass
            elements=ligne.strip().split(',')

            for z,e in enumerate(elements):
                elements[z]=e.strip('"').strip()
            if len(elements)>1:
                if i>0:
                    if not test_agency=='ZZ':
                        elements=elements+[prefixe]
                    l=[elements[iroute],elements[iagency]]
                    l.extend([elements[k] for k in set_route])
                    lignes[elements[iroute]]=l
                else:
                    if ("agency_id") not in elements:
                        test_agency=prefixe
                        elements=elements+["agency_id"]
                    iroute=elements.index("route_id")
                    iagency=elements.index("agency_id")
                    set_route=set([k for k in range(len(elements))])-set([iroute,iagency])
                    hroute=[elements[iroute],elements[iagency]]
                    
                    hroute.extend([elements[k] for k in set_route])
                    hroute=','.join(hroute)+"\n"
                
        routes.close()
        
        services={}        
        trips=io.open(rep+'/trips.txt','r',encoding=encodage)
        for i,ligne in enumerate(trips):

            try:
                test=ligne.startswith(codecs.BOM_UTF8)
                if test:
                    ligne=ligne[3:]
            except:
                pass
            elements=ligne.strip().split(',')

            for i1,i2 in enumerate(elements):
                elements[i1]=i2.strip('"').strip()
                
            if len(elements)>1:
                if i>0:
                    if elements[iroute] in lignes:
                        if len(elements)>6:
                            if elements[6] not in ['',None]:
                                elements[6]=prefixe+elements[6]
                        t=[elements[iroute],elements[iservice],elements[itrip]]
                        t.extend(elements[3:])
                        services[elements[itrip]]=t
                else:
                    for z,e in enumerate(elements):
                        elements[z]=e.strip('"').strip()
                    iroute=elements.index("route_id")
                    itrip=elements.index("trip_id")
                    iservice=elements.index("service_id")
                    htrip=[elements[iroute],elements[iservice],elements[itrip]]
                    htrip.extend(elements[3:])
                    htrip=(','.join(htrip))
                    #htrip=htrip.encode('cp1252')+"\n"
        trips.close()

        
        horaires={}
        stop_times=io.open(rep+'/stop_times.txt','r',encoding=encodage)
        montee_descente=False
        test_ligne=True
        for i,ligne in enumerate(stop_times):
            #ligne=ligne.decode('utf-8')
            try:
                test=ligne.startswith(codecs.BOM_UTF8)
                if test:
                    ligne=ligne[3:]
            except:
                pass
            elements=ligne.strip().split(',')
            for z,e in enumerate(elements):
                elements[z]=e.strip('"').strip()

            if len(elements)>1:
                if i>0:
                    if montee_descente==True:
                        if (elements[boa] in ['0',''] or elements[ali] in ['0','']):
                            test_ligne=True
                        else:
                            test_ligne=False
                            
                    if test_ligne==True:
                        if elements[itrip] in services:
                            elements[iarr]=elements[iarr].strip('"').zfill(8)
                            elements[idep]=elements[idep].strip('"').zfill(8)
                            if uic==True:
                                elements[istop]=eval("elements[istop]"+formula)
                                o=[elements[itrip],elements[iarr],elements[idep],elements[istop],elements[iseq]]
                            else:
                                try:
                                    o=[elements[itrip],elements[iarr],elements[idep],elements[istop],elements[iseq]]
                                except:
                                    print(elements)
                        o.extend(elements[5:])
                        if elements[0] not in horaires:
                            horaires[elements[0]]={}
                        if len(elements)>5 and elements[itrip] in htrip:
                            horaires[elements[itrip]][int(elements[iseq])]=[int(elements[iseq]),elements[istop],elements[iarr],elements[idep],elements[5]]
                        else:
                            try:
                                horaires[elements[itrip]][int(elements[iseq])]=[int(elements[iseq]),elements[istop],elements[iarr],elements[idep]]
                            except:
                                print(elements)
                else:
                    iarr=elements.index("arrival_time")
                    idep=elements.index("departure_time")
                    itrip=elements.index("trip_id")
                    istop=elements.index("stop_id")
                    iseq=elements.index("stop_sequence")
                    hstop_times=[elements[itrip],elements[iarr],elements[idep],elements[istop],elements[iseq]]
                    #hstop_times.extend(elements[5:])
                    hstop_times=','.join(hstop_times)
                    if ('pickup_type' in elements) and ('drop_off_type' in elements):
                        boa=elements.index("pickup_type")
                        ali=elements.index("drop_off_type")
                        montee_descente=True


        stop_times.close()
        
        
        
        formes={}
        if (os.path.isfile(rep+'/shapes.txt')==True):
            shapes=io.open(rep+'/shapes.txt','r',encoding=encodage)
            if not os.path.isdir(sortie+"/"+prefixe):
                os.mkdir(sortie+"/"+prefixe)

            shapes2=codecs.open(sortie+"/"+prefixe+'/shapes.txt','w',encoding='utf_8_sig')
            for i,ligne in enumerate(shapes):
                #ligne=ligne.decode('utf-8')
                elements=ligne.strip().split(',')
                if len(elements)>1:
                    if i>0:
                        elements[0]=prefixe+elements[0]
                    shapes2.write(",".join(elements)+"\n")
            shapes.close()
            shapes2.close()

                    
                    

        calsem={}
        if ("calendar.txt" in os.listdir(rep)):
            cal=io.open(rep+'/calendar.txt','r',encoding=encodage)
            for i,ligne in enumerate(cal):
                try:
                    test=ligne.startswith(codecs.BOM_UTF8)
                    if test:
                        ligne=ligne[3:]
                except:
                    pass
                elements=ligne.strip().split(',')
                for z,e in enumerate(elements):
                    elements[z]=e.strip('"').strip()
                if len(elements)>1:
                    if i>0:
                        elements[0]=prefixe+elements[0]
                        calsem[elements[0]]=elements
                    else:
                        hcalsem=ligne
            cal.close()
        
        caldates={}
        if ("calendar_dates.txt" in os.listdir(rep)):
            cald=io.open(rep+'/calendar_dates.txt','r',encoding=encodage)
            for i,ligne in enumerate(cald):
                try:
                    test=ligne.startswith(codecs.BOM_UTF8)
                    if test:
                        ligne=ligne[3:]
                except:
                    pass
                if ligne not in ['\n',None,'',u'\r\n']:
                    elements=ligne.strip().split(',')
                    for z,e in enumerate(elements):
                        elements[z]=e.strip('"').strip()
                    elements[1]=elements[1].zfill(8)
                    if len(elements)>1:
                        if i>0:
                            elements[0]=prefixe+elements[0]
                            caldates[(elements[0],elements[1])]=elements
                        else:
                            hcaldate=ligne
            cald.close()
        
        chainages={}
        for service in services:
            if service in horaires:
                horaires[service]=sorted(horaires[service].values(),key=lambda x:x[0])
                chaine=list(zip(*(horaires[service])))[1]
                if chaine not in chainages:
                    chainages[chaine]=[]
                chainages[chaine].append(service)
        
        if not os.path.isdir(sortie+"/"+prefixe):
            os.mkdir(sortie+"/"+prefixe)
            
        routes2=codecs.open(sortie+"/"+prefixe+'/routes.txt','w',encoding='utf_8_sig')
        #if test_agency<>'ZZ':
        #hroute=",".join(hroute.split(",")[:-1])
        routes2.write(hroute)
        #trips2=open(sortie+'/trips.txt','w')
        trips2=codecs.open(sortie+"/"+prefixe+"/trips.txt","w",encoding='utf_8_sig')
        trips2.write(htrip+"\n")
        #stops2=open(sortie+'/stops.txt','w')
        stops2=codecs.open(sortie+"/"+prefixe+"/stops.txt","w",encoding='utf_8_sig')
        stops2.write(hstops+"\n")
        stop_times2=codecs.open(sortie+"/"+prefixe+'/stop_times.txt','w',encoding='utf_8_sig')
        stop_times2.write(hstop_times+"\n")
        if ("calendar.txt" in os.listdir(rep)):
            cal2=codecs.open(sortie+"/"+prefixe+'/calendar.txt','w',encoding='utf_8_sig')
            cal2.write(hcalsem)
        if ("calendar_dates.txt" in os.listdir(rep)):
            cald2=codecs.open(sortie+"/"+prefixe+'/calendar_dates.txt','w',encoding='utf_8_sig')
            cald2.write(hcaldate)

        
        
        for i,chaine in enumerate(chainages):
            s=chainages[chaine][0]
            trip=services[s]
            route=lignes[services[s][0]]
            if not test_agency=='ZZ':
                route=route
            routes2.write((prefixe+str(i)+","+",".join(route[1:])+"\n"))
            for j,service in enumerate(chainages[chaine]):
                trip=services[service]
                trips2.write((prefixe+str(i)+","+prefixe+trip[1]+","+prefixe+trip[2]+','+",".join(trip[3:])+"\n"))
                hh=horaires[service]
                for h in hh:
                    if len(h)>4:
                        stop_times2.write((prefixe+trip[2]+","+h[2]+","+h[3]+","+prefixe+h[1]+","+str(h[0])+","+h[4]+"\n"))
                    else:
                        stop_times2.write((prefixe+trip[2]+","+h[2]+","+h[3]+","+prefixe+h[1]+","+str(h[0])+"\n"))
        routes2.close()
        trips2.close()
        stop_times2.close()
        
        
        for stop in arrets:
            arrets[stop][iname]='"'+arrets[stop][iname]+'"'
            if "stop_desc" in hstops.split(','):
                 arrets[stop][idesc]='"'+arrets[stop][idesc]+'"'
            stops2.write((",".join(arrets[stop])+"\n"))
        stops2.close()
        
        
        for c in calsem:
            cal2.write((",".join(calsem[c])+"\n"))
        for c in caldates:
            cald2.write((",".join(caldates[c])+"\n"))
        if ("calendar.txt" in os.listdir(rep)):
            cal2.close()
        if ("calendar_dates.txt" in os.listdir(rep)):
            cald2.close()




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

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

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

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

    def tr(self, string):
        return QCoreApplication.translate('PrepareGTFS', string)
        
    def shortHelpString(self):
        return self.tr("""
        Scan a GTFS Folder and generates a well-formated GTFS consistent with Musliw in particular for lines 
        
        Parameters:
        GTFS source folder: the folder of the GTFS source files
        GTFS destination folder: folder of the Musliw well formated GTFS
        Network id: id in order to differenciate networks (line ID, stop ID,...) (ex: LI and 15696 -> stop_id LI15696
        Extract stop_id: if true the user must write a formula to extract the stop_id from the initial node_id string
        Extract formula: the formula to extract stop_id: (ex: "OCE:StopArea:87256315") with [-8:] formula -> "OCE:StopArea:87256315"[-8:]="87256315"
        """)
        
    def createInstance(self):
        return PrepareGTFS()
