"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.RefreshPublicGtfsDepartureCacheTask = void 0;
const PublicGtfsDepartureRepository_1 = require("../../../data-access/cache/PublicGtfsDepartureRepository");
const precomputed_1 = require("../../../data-access/precomputed");
const RopidGtfsContainerToken_1 = require("../../../ioc/RopidGtfsContainerToken");
const PublicDepartureCacheTransformation_1 = require("../../../transformations/PublicDepartureCacheTransformation");
const CoreToken_1 = require("@golemio/core/dist/helpers/ioc/CoreToken");
const workers_1 = require("@golemio/core/dist/integration-engine/workers");
const golemio_errors_1 = require("@golemio/core/dist/shared/golemio-errors");
const tsyringe_1 = require("@golemio/core/dist/shared/tsyringe");
const constants_1 = require("../constants");
const RefreshPublicDepartureSchema_1 = require("./schema/RefreshPublicDepartureSchema");
const RopidGTFSStopsModel_1 = require("../../../RopidGTFSStopsModel");
const DEFAULT_PAGE_SIZE = 50000;
let RefreshPublicGtfsDepartureCacheTask = class RefreshPublicGtfsDepartureCacheTask extends workers_1.AbstractTask {
    constructor(departureTransformation, departureRepository, publicDepartureRepository, config, stopsModel) {
        super(constants_1.TIMETABLE_WORKER_NAME);
        this.departureTransformation = departureTransformation;
        this.departureRepository = departureRepository;
        this.publicDepartureRepository = publicDepartureRepository;
        this.config = config;
        this.stopsModel = stopsModel;
        this.queueName = "refreshPublicGtfsDepartureCache";
        this.queueTtl = 59 * 60 * 1000; // 59 minutes
        this.schema = RefreshPublicDepartureSchema_1.RefreshPublicDepartureValidationSchema;
        const departurePageSize = this.config.getValue("module.pid.ropid-gtfs.timetables.refreshPublicGtfsDepartureCache.departurePageSize", DEFAULT_PAGE_SIZE.toString());
        this.departurePageSize = Number.parseInt(departurePageSize);
    }
    async execute(params) {
        const intervalParams = this.getIntervalParamsWithDefault(params);
        const numberOfDepartures = await this.departureRepository.countDeparturesForPublicCache(intervalParams);
        const pages = Math.ceil(numberOfDepartures / this.departurePageSize);
        const stopIdsInDepartures = new Set();
        for (let page = 0; page < pages; page++) {
            const departuresForCache = await this.departureRepository.getDepaturesForPublicCache(page, this.departurePageSize, intervalParams);
            const departuresByStopIdDict = this.getDeparturesByStopId(departuresForCache);
            for (const [stopId, departures] of departuresByStopIdDict.entries()) {
                stopIdsInDepartures.add(stopId);
                try {
                    const departuresDto = this.departureTransformation.transformArray(departures);
                    await this.publicDepartureRepository.replaceDeparturesForStop(departuresDto, stopId, intervalParams);
                }
                catch (err) {
                    if (err instanceof golemio_errors_1.AbstractGolemioError) {
                        throw err;
                    }
                    throw new golemio_errors_1.GeneralError("Error while refreshing public departure cache", this.constructor.name, err);
                }
            }
        }
        const allStops = await this.stopsModel.getAll();
        for (const { stop_id: id } of allStops) {
            if (!stopIdsInDepartures.has(id)) {
                await this.publicDepartureRepository.replaceDeparturesForStop([], id, intervalParams);
            }
        }
    }
    getIntervalParamsWithDefault(params) {
        const defaultIntervalFromHours = this.config.getValue("module.pid.ropid-gtfs.timetables.refreshPublicGtfsDepartureCache.defaultIntervalFromHours", "-3");
        const defaultIntervalToHours = this.config.getValue("module.pid.ropid-gtfs.timetables.refreshPublicGtfsDepartureCache.defaultIntervalToHours", "6");
        return {
            intervalFromHours: params.intervalFromHours ?? Number.parseInt(defaultIntervalFromHours),
            intervalToHours: params.intervalToHours ?? Number.parseInt(defaultIntervalToHours),
        };
    }
    getDeparturesByStopId(departures) {
        const departuresByStopId = new Map();
        for (const departure of departures) {
            if (!departuresByStopId.has(departure.stop_id)) {
                departuresByStopId.set(departure.stop_id, []);
            }
            departuresByStopId.get(departure.stop_id).push(departure);
        }
        return departuresByStopId;
    }
};
exports.RefreshPublicGtfsDepartureCacheTask = RefreshPublicGtfsDepartureCacheTask;
exports.RefreshPublicGtfsDepartureCacheTask = RefreshPublicGtfsDepartureCacheTask = __decorate([
    (0, tsyringe_1.injectable)(),
    __param(0, (0, tsyringe_1.inject)(RopidGtfsContainerToken_1.RopidGtfsContainerToken.PublicDepartureCacheTransformation)),
    __param(1, (0, tsyringe_1.inject)(RopidGtfsContainerToken_1.RopidGtfsContainerToken.DepartureRepository)),
    __param(2, (0, tsyringe_1.inject)(RopidGtfsContainerToken_1.RopidGtfsContainerToken.PublicGtfsDepartureRepository)),
    __param(3, (0, tsyringe_1.inject)(CoreToken_1.CoreToken.SimpleConfig)),
    __param(4, (0, tsyringe_1.inject)(RopidGtfsContainerToken_1.RopidGtfsContainerToken.RopidGTFSStopsModel)),
    __metadata("design:paramtypes", [PublicDepartureCacheTransformation_1.PublicDepartureCacheTransformation,
        precomputed_1.DeparturesRepository,
        PublicGtfsDepartureRepository_1.PublicGtfsDepartureRepository, Object, RopidGTFSStopsModel_1.RopidGTFSStopsModel])
], RefreshPublicGtfsDepartureCacheTask);
//# sourceMappingURL=RefreshPublicGtfsDepartureCacheTask.js.map