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

"""
/***************************************************************************
 GIS2GTFS
                                 A QGIS plugin
 This plugin turns GIS files to GTFS feed
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2025-07-02
        copyright            : (C) 2025 by Transport for Cairo
        email                : info@transportforcairo.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__ = 'Transport for Cairo'
__date__ = '2025-07-02'
__copyright__ = '(C) 2025 by Transport for Cairo'

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

__revision__ = '$Format:%H$'

from qgis.PyQt.QtCore import QCoreApplication
from qgis.core import (QgsProcessing,
                       QgsFeatureSink,
                       QgsProcessingAlgorithm,
                       QgsProcessingParameterFeatureSource,
                       QgsProcessingParameterFeatureSink,
                       QgsProcessingParameterProviderConnection, # added
                       QgsProcessingParameterFolderDestination,
                       QgsProcessingParameterString,
                       QgsProcessingParameterBoolean)  
import os
from .build import run_gtfs_pipeline

# for icon
from qgis.PyQt.QtGui import QIcon

def _icon_path(*parts):
    # __file__ is inside tfc_tools/rl2sdi/
    here = os.path.dirname(__file__)
    root = os.path.abspath(os.path.join(here, ".."))     # tfc_tools/
    return os.path.join(root, *parts)


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

    CONN_NAME = 'CONN_NAME'
    DATA_RAW_DIR = 'DATA_RAW_DIR'
    DATA_DIR = 'DATA_DIR'
    FEED_NAME = 'FEED_NAME'
    START_DATE = 'START_DATE'
    END_DATE = 'END_DATE'
    SERVICE_ID = 'SERVICE_ID'
    CONTINUOUS = 'CONTINUOUS'

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

        # 1. SDI DB connection
        self.addParameter(
            QgsProcessingParameterProviderConnection(
                self.CONN_NAME,
                self.tr('PostgreSQL SDI Connection'),  # in rl2sdi plugin format it would've just been "PostgreSQL SDI Connection"
                provider='postgres'
            )
        )

        # 2. OUTPUT FOLDER 1 (FOR RAW DATA FROM SDI)
        self.addParameter(
            QgsProcessingParameterFolderDestination(
                self.DATA_RAW_DIR,
                self.tr('Output folder for intermediate raw data')
            )
        )

        # 3. OUTPUT FOLDER 2 (FOR GTFS OUTPUT)
        self.addParameter(
            QgsProcessingParameterFolderDestination(
                self.DATA_DIR,
                self.tr('Output folder for GTFS data')
            )
        )

        # 4. OTHER NEEDED INPUT 
        self.addParameter(
            QgsProcessingParameterString(
                self.FEED_NAME,
                # self.tr('Feed name (e.g., cairo)')
                self.tr('Feed version')
            )
        )

        self.addParameter(
            QgsProcessingParameterString(
                self.START_DATE,
                self.tr('Start date (YYYYMMDD)')
            )
        )

        self.addParameter(
            QgsProcessingParameterString(
                self.END_DATE,
                self.tr('End date (YYYYMMDD)')
            )
        )

        self.addParameter(
            QgsProcessingParameterString(
                self.SERVICE_ID,
                self.tr('Service ID (e.g., Ground_Daily)')
            )
        )

        self.addParameter(
            QgsProcessingParameterBoolean(
                self.CONTINUOUS,
                self.tr('Use continuous drop-off/pick-up'),
                defaultValue=True
            )
        )


    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        conn_name = self.parameterAsString(parameters, self.CONN_NAME, context)
        data_raw_dir = self.parameterAsString(parameters, self.DATA_RAW_DIR, context)
        data_dir = self.parameterAsString(parameters, self.DATA_DIR, context)
        feed_name = self.parameterAsString(parameters, self.FEED_NAME, context)
        start_date = int(self.parameterAsString(parameters, self.START_DATE, context))
        end_date = int(self.parameterAsString(parameters, self.END_DATE, context))
        service_id = self.parameterAsString(parameters, self.SERVICE_ID, context)
        continuous = self.parameterAsBool(parameters, self.CONTINUOUS, context)

        # Call the GTFS build pipeline
        run_gtfs_pipeline(
            conn_name=conn_name,
            data_raw_dir=data_raw_dir,
            data_dir=data_dir,
            feed_name=feed_name,
            feed_start_date=start_date,
            feed_end_date=end_date,
            feed_version=1,
            feed_lang="en",  #maybe later we can let the user choose the feed_lang
            start_date=start_date,
            end_date=end_date,
            service_id=service_id,
            continuous_dropoff_pickup=continuous,
            dwell_time_sec=15   #check if we want to let the user choose the value
        )

        return {}

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

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

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

    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 'GIS tools'
        return 'gis_tools'
    
    def shortHelpString(self):
        return self.tr("This algorithm build a GTFS feed from spatial database layers.")  # later revise this text here

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

    def createInstance(self):
        return GIS2GTFSAlgorithm()
    
    def icon(self):
        return QIcon(_icon_path("icons", "GIS-icon.svg"))
    # Optional: some QGIS builds prefer this for SVG
    def svgIconPath(self):
        return _icon_path("icons", "GIS-icon.svg")
