"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.RefreshPublicStopTimeCacheTask = void 0;
const VPContainerToken_1 = require("../../../ioc/VPContainerToken");
const VehicleIdGenerator_1 = require("../../gtfs-rt/helpers/VehicleIdGenerator");
const IoRedisConnector_1 = require("@golemio/core/dist/helpers/data-access/redis/IoRedisConnector");
const CoreToken_1 = require("@golemio/core/dist/helpers/ioc/CoreToken");
const integration_engine_1 = require("@golemio/core/dist/integration-engine");
const ioc_1 = require("@golemio/core/dist/integration-engine/ioc");
const workers_1 = require("@golemio/core/dist/integration-engine/workers");
const golemio_errors_1 = require("@golemio/core/dist/shared/golemio-errors");
const redis_semaphore_1 = require("@golemio/core/dist/shared/redis-semaphore");
const tsyringe_1 = require("@golemio/core/dist/shared/tsyringe");
const promises_1 = require("node:timers/promises");
const constants_1 = require("../constants");
const PublicStopTimeCacheRepository_1 = require("../data-access/cache/PublicStopTimeCacheRepository");
const PublicStopTimeRepository_1 = require("../data-access/views/PublicStopTimeRepository");
const VPUtils_1 = require("../helpers/VPUtils");
let RefreshPublicStopTimeCacheTask = class RefreshPublicStopTimeCacheTask extends workers_1.AbstractEmptyTask {
    constructor(config, logger, redisClient, publicStopTimeRepository, publicStopTimeCacheRepository) {
        super(constants_1.WORKER_NAME);
        this.logger = logger;
        this.redisClient = redisClient;
        this.publicStopTimeRepository = publicStopTimeRepository;
        this.publicStopTimeCacheRepository = publicStopTimeCacheRepository;
        this.queueName = "refreshPublicStopTimeCache";
        this.queueTtl = 10000; // 10s
        this.lockTimeout = config.getValue("old.datasources.pid.vehicle-positions.publicCache.mutexLockStopTimeTimeout", 6000); // default 6s
        this.refreshInterval = this.lockTimeout * constants_1.LOCK_REFRESH_INTERVAL_RATIO;
    }
    async execute() {
        const startDateTime = new Date();
        const mutex = this.createMutex();
        const lockAcquired = await mutex.tryAcquire();
        if (!lockAcquired) {
            this.logger.info(`${this.constructor.name}: mutex lock was not acquired`);
            return;
        }
        try {
            const stopTimes = await this.publicStopTimeRepository.findAll();
            if (stopTimes.length === 0) {
                return;
            }
            let ellapsedTimeInMs = new Date().getTime() - startDateTime.getTime();
            this.logger.info(`${this.constructor.name}: fetched ${stopTimes.length} stop times in ${ellapsedTimeInMs}ms`);
            const data = new Map();
            for (const stopTime of stopTimes) {
                const vehicleId = VehicleIdGenerator_1.VehicleIdGenerator.getVehicleId(stopTime.rt_trip_id, stopTime.gtfs_route_type, stopTime.provider_source_type, stopTime.gtfs_route_short_name, stopTime.cis_trip_number, stopTime.vehicle_registration_number, stopTime.run_number, stopTime.internal_run_number);
                const key = `${vehicleId}-${stopTime.gtfs_trip_id}`;
                if (!data.has(key)) {
                    data.set(key, []);
                }
                data.get(key).push({
                    sequence: stopTime.stop_sequence,
                    arr_delay: stopTime.stop_arr_delay,
                    dep_delay: stopTime.stop_dep_delay,
                    cis_stop_platform_code: stopTime.cis_stop_platform_code,
                    platform_code: stopTime.platform_code,
                    stop_id: stopTime.stop_id,
                    stop_name: stopTime.stop_name,
                });
            }
            ellapsedTimeInMs = new Date().getTime() - startDateTime.getTime();
            this.logger.info(`${this.constructor.name}: transformed ${stopTimes.length} stop times to ` +
                `${data.size} keys in ${ellapsedTimeInMs}ms`);
            // this operation can block redis connection, which may cause the mutex lock to expire
            await this.publicStopTimeCacheRepository.createOrUpdate(data, VPUtils_1.VPUtils.DELAY_COMPUTATION_CACHE_TTL);
        }
        catch (err) {
            if (err instanceof golemio_errors_1.AbstractGolemioError) {
                throw err;
            }
            throw new golemio_errors_1.GeneralError(`${this.constructor.name}: error while refreshing public stop time cache`, this.constructor.name, err);
        }
        finally {
            await mutex.release();
        }
        const ellapsedTimeInMs = new Date().getTime() - startDateTime.getTime();
        this.logger.info(`${this.constructor.name}: finished in ${ellapsedTimeInMs}ms`);
        if (ellapsedTimeInMs < this.refreshInterval) {
            await (0, promises_1.setTimeout)(this.refreshInterval - ellapsedTimeInMs);
        }
        integration_engine_1.QueueManager.sendMessageToExchange(this.queuePrefix, this.queueName, {});
    }
    createMutex() {
        return new redis_semaphore_1.Mutex(this.redisClient.getConnection(), this.queueName, {
            acquireAttemptsLimit: 1,
            lockTimeout: this.lockTimeout,
            refreshInterval: this.refreshInterval,
            onLockLost: (err) => {
                this.logger.error(err, `${this.constructor.name}: mutex lock was lost`);
            },
        });
    }
};
exports.RefreshPublicStopTimeCacheTask = RefreshPublicStopTimeCacheTask;
exports.RefreshPublicStopTimeCacheTask = RefreshPublicStopTimeCacheTask = __decorate([
    (0, tsyringe_1.injectable)(),
    __param(0, (0, tsyringe_1.inject)(CoreToken_1.CoreToken.SimpleConfig)),
    __param(1, (0, tsyringe_1.inject)(CoreToken_1.CoreToken.Logger)),
    __param(2, (0, tsyringe_1.inject)(ioc_1.ContainerToken.RedisConnector)),
    __param(3, (0, tsyringe_1.inject)(VPContainerToken_1.VPContainerToken.PublicStopTimeRepository)),
    __param(4, (0, tsyringe_1.inject)(VPContainerToken_1.VPContainerToken.PublicStopTimeCacheRepository)),
    __metadata("design:paramtypes", [Object, Object, IoRedisConnector_1.IoRedisConnector,
        PublicStopTimeRepository_1.PublicStopTimeRepository,
        PublicStopTimeCacheRepository_1.PublicStopTimeCacheRepository])
], RefreshPublicStopTimeCacheTask);
//# sourceMappingURL=RefreshPublicStopTimeCacheTask.js.map