"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); }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UpdateRunsGtfsTripIdTask = void 0;
const cache_1 = require("../../../../ropid-gtfs/data-access/cache");
const CommonRunsRepository_1 = require("../../runs/data-access/CommonRunsRepository");
const VPContainerToken_1 = require("../../../ioc/VPContainerToken");
const helpers_1 = require("@golemio/core/dist/integration-engine/helpers");
const queueprocessors_1 = require("@golemio/core/dist/integration-engine/queueprocessors");
const workers_1 = require("@golemio/core/dist/integration-engine/workers");
const tsyringe_1 = require("@golemio/core/dist/shared/tsyringe");
const PositionsRepository_1 = require("../data-access/PositionsRepository");
const PositionsMapper_1 = __importDefault(require("../data-access/helpers/PositionsMapper"));
const TripsIdGenerator_1 = __importDefault(require("../data-access/helpers/TripsIdGenerator"));
const TripsMapper_1 = __importDefault(require("../data-access/helpers/TripsMapper"));
const GTFSTripRunManagerFactory_1 = require("../helpers/gtfs-trip-run/GTFSTripRunManagerFactory");
const UpdateRunsGtfsTripIdSchema_1 = require("../schema/UpdateRunsGtfsTripIdSchema");
const constants_1 = require("../constants");
let UpdateRunsGtfsTripIdTask = class UpdateRunsGtfsTripIdTask extends workers_1.AbstractTask {
    constructor(tripsRepository, positionsRepository, commonRunsRepository, runTripsRedisRepository) {
        super(constants_1.WORKER_NAME);
        this.queueName = "updateRunsGTFSTripId";
        this.queueTtl = 5 * 60 * 1000; // 5 minutes
        this.schema = UpdateRunsGtfsTripIdSchema_1.UpdateRunsGtfsTripIdValidationSchema;
        /**
         * Process not public trips from runs data
         */
        this.updateNotPublicRunTrip = async (input) => {
            const tripId = TripsIdGenerator_1.default.generateFromCommonRunNotPublic(input.run);
            //#region position
            const positionDto = PositionsMapper_1.default.mapCommonRunNotPublicToDto(input.run_message, tripId);
            const createdPosition = await this.positionsRepository.createEntity(positionDto);
            //#endregion
            //#region trip
            const tripDto = TripsMapper_1.default.mapCommonRunNotPublicToDto(input.run, tripId, createdPosition.id, input.notPublicVehicleRouteType);
            await this.tripsRepository.upsertEntity(tripDto);
            //#endregion
        };
        this.tripsRepository = tripsRepository;
        this.positionsRepository = positionsRepository;
        this.commonRunsRepository = commonRunsRepository;
        this.runTripsRedisRepository = runTripsRedisRepository;
        this.gtfsTripRunManager = GTFSTripRunManagerFactory_1.GTFSTripRunManagerFactory.create(GTFSTripRunManagerFactory_1.GTFSTripRunType.Common, positionsRepository, tripsRepository, commonRunsRepository, runTripsRedisRepository);
    }
    /**
     * Process trips from runs data
     */
    async execute(data, messageProperties) {
        const schedule = await this.gtfsTripRunManager.setAndReturnScheduledTrips(data.run);
        if (schedule.length === 0) {
            // Use the isNotPublic flag set by the filter to avoid duplicate Redis calls
            // This flag is true if the vehicle is whitelisted by registration number or route name
            if (data.isNotPublic === true) {
                await this.updateNotPublicRunTrip(data);
            }
            else {
                helpers_1.log.info(`updateRunsGTFSTripId: no schedule for run: ${JSON.stringify(data.run)}`);
            }
            return;
        }
        if (!data.run_message.actual_stop_timestamp_scheduled) {
            helpers_1.log.info(`updateRunsGTFSTripId: actualStopTimestampScheduled is not provided for current run: ${JSON.stringify(data.run)}`);
            return;
        }
        const delayMsg = await this.gtfsTripRunManager.generateDelayMsg(schedule, data);
        // send to updateDelay only if there are some trips updated
        if (delayMsg.updatedTrips.length > 0) {
            await queueprocessors_1.QueueManager.sendMessageToExchange(this.queuePrefix, "updateDelay", delayMsg, {
                timestamp: messageProperties?.timestamp,
            });
        }
    }
};
exports.UpdateRunsGtfsTripIdTask = UpdateRunsGtfsTripIdTask;
exports.UpdateRunsGtfsTripIdTask = UpdateRunsGtfsTripIdTask = __decorate([
    (0, tsyringe_1.injectable)(),
    __param(0, (0, tsyringe_1.inject)(VPContainerToken_1.VPContainerToken.TripRepository)),
    __param(1, (0, tsyringe_1.inject)(VPContainerToken_1.VPContainerToken.PositionsRepository)),
    __param(2, (0, tsyringe_1.inject)(VPContainerToken_1.VPContainerToken.CommonRunsRepository)),
    __param(3, (0, tsyringe_1.inject)(VPContainerToken_1.VPContainerToken.RunTripsRedisRepository)),
    __metadata("design:paramtypes", [Function, PositionsRepository_1.PositionsRepository,
        CommonRunsRepository_1.CommonRunsRepository,
        cache_1.RunTripsRedisRepository])
], UpdateRunsGtfsTripIdTask);
//# sourceMappingURL=UpdateRunsGtfsTripIdTask.js.map