"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 PublicGtfsDepartureRepository_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PublicGtfsDepartureRepository = void 0;
const const_1 = require("../../../../schema-definitions/ropid-gtfs/redis/const");
const PublicGtfsDepartureDtoSchema_1 = require("../../../../schema-definitions/ropid-gtfs/redis/schemas/PublicGtfsDepartureDtoSchema");
const RedisModel_1 = require("@golemio/core/dist/integration-engine/models/RedisModel");
const golemio_errors_1 = require("@golemio/core/dist/shared/golemio-errors");
const golemio_validator_1 = require("@golemio/core/dist/shared/golemio-validator");
const tsyringe_1 = require("@golemio/core/dist/shared/tsyringe");
let PublicGtfsDepartureRepository = PublicGtfsDepartureRepository_1 = class PublicGtfsDepartureRepository extends RedisModel_1.RedisModel {
    constructor() {
        super("GtfsDepartureRepository", {
            decodeDataAfterGet: JSON.parse,
            encodeDataBeforeSave: JSON.stringify,
            isKeyConstructedFromData: false,
            prefix: PublicGtfsDepartureRepository_1.NAMESPACE_PREFIX,
        }, new golemio_validator_1.JSONSchemaValidator("PublicGtfsDepartureRepositoryValidator", PublicGtfsDepartureDtoSchema_1.PublicGtfsDepartureDtoSchema));
    }
    /**
     * Save new departures for a stop and
     *   - remove all older departures
     *   - remove departures that are in the same time range as the new ones
     *     (to prevent duplicates and to keep the cache clean and up-to-date)
     */
    async replaceDeparturesForStop(departures, stopId, intervalParams) {
        try {
            await this.validator.Validate(departures);
        }
        catch (err) {
            throw new golemio_errors_1.ValidationError("Error while validating departures", this.constructor.name, err);
        }
        try {
            const sortedSetKey = `${this.prefix}:${stopId}`;
            const pipeline = this.connection.pipeline();
            // Automatically remove departures that are older than 3 hours to keep the cache clean
            pipeline.zremrangebyscore(sortedSetKey, "-inf", new Date().getTime() / 1000 - 3 * 3600);
            if (departures.length === 0) {
                // If stop already has an empty object it will just update the empty objects score/time
                pipeline.zadd(sortedSetKey, new Date().getTime() / 1000, "{}");
            }
            else {
                // remove empty departures from stop
                pipeline.zrem(sortedSetKey, "{}");
                const firstDepartureScore = new Date(departures[0].departure_datetime).getTime() / 1000;
                const lastDepartureScore = new Date(departures[departures.length - 1].departure_datetime).getTime() / 1000;
                // Remove departures that are in the same time range
                pipeline.zremrangebyscore(sortedSetKey, firstDepartureScore, lastDepartureScore);
                for (const departure of departures) {
                    const departureScore = new Date(departure.departure_datetime).getTime() / 1000;
                    pipeline.zadd(sortedSetKey, departureScore, JSON.stringify(departure));
                }
            }
            pipeline.expire(sortedSetKey, intervalParams.intervalToHours * 3600);
            await pipeline.exec();
        }
        catch (err) {
            if (err instanceof golemio_errors_1.AbstractGolemioError) {
                throw err;
            }
            throw new golemio_errors_1.GeneralError(`${this.constructor.name}: error while saving departures`, this.constructor.name, err);
        }
    }
};
exports.PublicGtfsDepartureRepository = PublicGtfsDepartureRepository;
PublicGtfsDepartureRepository.NAMESPACE_PREFIX = const_1.PUBLIC_DEPARTURE_NAMESPACE_PREFIX;
exports.PublicGtfsDepartureRepository = PublicGtfsDepartureRepository = PublicGtfsDepartureRepository_1 = __decorate([
    (0, tsyringe_1.injectable)(),
    __metadata("design:paramtypes", [])
], PublicGtfsDepartureRepository);
//# sourceMappingURL=PublicGtfsDepartureRepository.js.map