"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PropagateTrainDelayTask = void 0;
const Di_1 = require("../../../../ropid-gtfs/ioc/Di");
const RopidGtfsContainerToken_1 = require("../../../../ropid-gtfs/ioc/RopidGtfsContainerToken");
const CoreToken_1 = require("@golemio/core/dist/helpers/ioc/CoreToken");
const ioc_1 = require("@golemio/core/dist/integration-engine/ioc");
const sequelize_1 = require("@golemio/core/dist/shared/sequelize");
const PropagateTrainDelaySchema_1 = require("../schema/PropagateTrainDelaySchema");
const AbstractPropagateDelayTask_1 = require("./abstract/AbstractPropagateDelayTask");
class PropagateTrainDelayTask extends AbstractPropagateDelayTask_1.AbstractPropagateDelayTask {
    constructor(queuePrefix) {
        super(queuePrefix);
        this.queueName = "propagateTrainDelay";
        this.queueTtl = 5 * 60 * 1000; // 5 minutes
        this.schema = PropagateTrainDelaySchema_1.PropagateDelayValidationSchema;
        this.getNextGtfsTripId = async (gtfs_block_id, start_timestamp) => {
            const trip = await this.tripsRepository.findOne({
                attributes: ["gtfs_trip_id"],
                where: {
                    gtfs_block_id: gtfs_block_id,
                    start_timestamp: { [sequelize_1.Op.gt]: start_timestamp },
                },
                order: [["start_timestamp", "ASC"]],
                raw: true,
            });
            return trip?.gtfs_trip_id;
        };
        this.logger = ioc_1.IntegrationEngineContainer.resolve(CoreToken_1.CoreToken.Logger);
        this.blockStopsRepository = Di_1.RopidGtfsContainer.resolve(RopidGtfsContainerToken_1.RopidGtfsContainerToken.BlockStopsRedisRepository);
        this.config = ioc_1.IntegrationEngineContainer.resolve(CoreToken_1.CoreToken.SimpleConfig);
        this.turnaroundEstimateInSeconds = this.config.getValue("module.pid.vehicle-positions.gtfsTripRun.turnaroundEstimateInSeconds", 0);
    }
    async execute(input) {
        for (const delayedPositions of input.data) {
            const { gtfs_trip_id, gtfs_block_id, vehicle_registration_number, start_timestamp, end_timestamp } = delayedPositions.trip;
            try {
                const nextGtfsTripId = await this.getNextGtfsTripId(gtfs_block_id, start_timestamp);
                if (!nextGtfsTripId) {
                    continue;
                }
                const blockedTrips = (await this.blockStopsRepository.get(gtfs_block_id));
                const lastStopCurrentTrip = blockedTrips[gtfs_trip_id]?.trip_stops?.at(-1)?.stop_id;
                const firstStopNextTrip = blockedTrips[nextGtfsTripId]?.trip_stops?.[0]?.stop_id;
                const requiredTurnaroundSeconds = lastStopCurrentTrip === firstStopNextTrip ? 0 : this.turnaroundEstimateInSeconds;
                await this.propagateDelayForGtfsTrip({
                    currentGtfsTripId: gtfs_trip_id,
                    currentGtfsBlockId: gtfs_block_id ?? null,
                    currentOriginTimestamp: delayedPositions.position.originTimestamp,
                    currentDelay: delayedPositions.position.delayInSeconds,
                    currentRegistrationNumber: vehicle_registration_number,
                    currentStartTime: start_timestamp,
                    currentEndTime: end_timestamp,
                    currentBearing: delayedPositions.position.bearing,
                    nextGtfsTrips: nextGtfsTripId
                        ? [
                            {
                                trip_id: nextGtfsTripId,
                                requiredTurnaroundSeconds: requiredTurnaroundSeconds,
                            },
                        ]
                        : [],
                    originPositionId: delayedPositions.position.originId,
                });
            }
            catch (err) {
                this.logger.warn(`${this.queueName}: could not propagate train delay for GTFS trip: ${gtfs_trip_id} - ${err.message}`);
            }
        }
    }
}
exports.PropagateTrainDelayTask = PropagateTrainDelayTask;
//# sourceMappingURL=PropagateTrainDelayTask.js.map