"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ProcessRegionalBusRunMessagesTask = void 0;
const RouteTypeEnums_1 = require("../../../../../helpers/RouteTypeEnums");
const RouteSubAgencyRepository_1 = require("../../../../ropid-gtfs/data-access/RouteSubAgencyRepository");
const VPContainerToken_1 = require("../../../ioc/VPContainerToken");
const vehicle_positions_1 = require("../../../../../schema-definitions/vehicle-positions");
const CoreToken_1 = require("@golemio/core/dist/helpers/ioc/CoreToken");
const integration_engine_1 = require("@golemio/core/dist/integration-engine");
const tsyringe_1 = require("@golemio/core/dist/shared/tsyringe");
const DescriptorRepository_1 = require("../../vehicle-descriptors/data-access/DescriptorRepository");
const GtfsTripRegionalBusRunManager_1 = require("../../vehicle-positions/helpers/regional-bus/gtfs-trip-run/GtfsTripRegionalBusRunManager");
const constants_1 = require("../constants");
const RegionalBusTransformedRunsSchema_1 = require("../schema/RegionalBusTransformedRunsSchema");
let ProcessRegionalBusRunMessagesTask = class ProcessRegionalBusRunMessagesTask extends integration_engine_1.AbstractTask {
    constructor(config, descriptorRepository, gtfsLookupManager, tripScheduleManager) {
        super(constants_1.WORKER_NAME);
        this.config = config;
        this.descriptorRepository = descriptorRepository;
        this.gtfsLookupManager = gtfsLookupManager;
        this.tripScheduleManager = tripScheduleManager;
        this.queueName = "processRegionalBusRunMessages";
        this.queueTtl = 5 * 60 * 1000; // 5 minutes
        this.schema = RegionalBusTransformedRunsSchema_1.RegionalBusTransformedRunsValidationSchema;
        this.routeSubAgencyRepository = new RouteSubAgencyRepository_1.RouteSubAgencyRepository();
        this.gtfsTripRunManager = new GtfsTripRegionalBusRunManager_1.GtfsTripRegionalBusRunManager();
    }
    async execute({ messages }, msgProperties) {
        let gtfsTripByExternalId = await this.getGtfsTripsFromCache(messages);
        const messagesWithoutGtfsData = messages.filter((message) => !gtfsTripByExternalId.has(message.external_trip_id));
        if (messagesWithoutGtfsData.length > 0) {
            const scheduleInputData = await this.getGtfsTripsFromDb(messagesWithoutGtfsData);
            for (const schedule of scheduleInputData) {
                gtfsTripByExternalId.set(schedule.cache_lookup_key, schedule);
            }
            await this.gtfsLookupManager.setGtfsScheduleLookup(scheduleInputData);
        }
        for (const message of messages) {
            const schedule = gtfsTripByExternalId.get(message.external_trip_id);
            if (!schedule) {
                continue;
            }
            const scheduledTrips = await this.gtfsTripRunManager.setAndReturnScheduledTrips(schedule);
            if (scheduledTrips.length === 0) {
                continue;
            }
            const runInput = {
                runMessage: message,
                gtfsTripId: schedule.gtfs_trip_id,
                isWheelchairAccessible: schedule.is_wheelchair_accessible,
                agencyName: schedule.agency_name,
            };
            const delayMsg = await this.gtfsTripRunManager.generateDelayMsg(scheduledTrips, runInput);
            if (delayMsg.updatedTrips.length > 0) {
                const rabbitExchangeName = this.config.getValue("env.RABBIT_EXCHANGE_NAME");
                await integration_engine_1.QueueManager.sendMessageToExchange(`${rabbitExchangeName}.${vehicle_positions_1.VehiclePositions.name.toLowerCase()}`, "processRegionalBusPositions", delayMsg, { timestamp: msgProperties?.timestamp });
            }
        }
    }
    async getGtfsTripsFromCache(messages) {
        const gtfsTripByExternalId = new Map();
        const scheduleInputData = await this.gtfsLookupManager.getScheduleInputData(messages);
        for (let i = 0; i < messages.length; i++) {
            const message = messages[i];
            const schedule = scheduleInputData[i];
            if (schedule) {
                gtfsTripByExternalId.set(message.external_trip_id, schedule);
                continue;
            }
        }
        return gtfsTripByExternalId;
    }
    async getGtfsTripsFromDb(messages) {
        let cisLineIds = new Set();
        let registrationNumbers = new Set();
        for (const message of messages) {
            cisLineIds.add(message.cis_line_id);
            registrationNumbers.add(message.registration_number);
        }
        const subAgencyEntities = await this.routeSubAgencyRepository.findSubAgenciesByCisLineIds(Array.from(cisLineIds));
        const descriptorEntities = await this.descriptorRepository.findAccessDescByRegistrationNumbers(Array.from(registrationNumbers), RouteTypeEnums_1.GTFSRouteTypeEnum.BUS);
        let scheduleInputData = [];
        for (const message of messages) {
            const scheduleInputItem = await this.tripScheduleManager.getScheduleInput(message, subAgencyEntities, descriptorEntities);
            if (!scheduleInputItem) {
                continue;
            }
            scheduleInputData.push(scheduleInputItem);
        }
        return scheduleInputData;
    }
};
exports.ProcessRegionalBusRunMessagesTask = ProcessRegionalBusRunMessagesTask;
exports.ProcessRegionalBusRunMessagesTask = ProcessRegionalBusRunMessagesTask = __decorate([
    (0, tsyringe_1.injectable)(),
    __param(0, (0, tsyringe_1.inject)(CoreToken_1.CoreToken.SimpleConfig)),
    __param(1, (0, tsyringe_1.inject)(VPContainerToken_1.VPContainerToken.DescriptorRepository)),
    __param(2, (0, tsyringe_1.inject)(VPContainerToken_1.VPContainerToken.GtfsLookupManager)),
    __param(3, (0, tsyringe_1.inject)(VPContainerToken_1.VPContainerToken.TripScheduleManager)),
    __metadata("design:paramtypes", [Object, DescriptorRepository_1.DescriptorRepository, Object, Object])
], ProcessRegionalBusRunMessagesTask);
//# sourceMappingURL=ProcessRegionalBusRunMessagesTask.js.map