"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 PublicStopTimeCacheRepository_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.PublicStopTimeCacheRepository = void 0;
const const_1 = require("../../../../../../schema-definitions/vehicle-positions/redis/const");
const PublicStopTimeCacheDtoSchema_1 = require("../../../../../../schema-definitions/vehicle-positions/redis/schemas/PublicStopTimeCacheDtoSchema");
const CoreToken_1 = require("@golemio/core/dist/helpers/ioc/CoreToken");
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 PublicStopTimeCacheRepository = PublicStopTimeCacheRepository_1 = class PublicStopTimeCacheRepository extends RedisModel_1.RedisModel {
    constructor(log) {
        super("PublicStopTimeCacheRepository", {
            isKeyConstructedFromData: false,
            prefix: PublicStopTimeCacheRepository_1.NAMESPACE_PREFIX,
        }, new golemio_validator_1.JSONSchemaValidator("PublicStopTimeCacheRepository", PublicStopTimeCacheDtoSchema_1.PublicStopTimeCacheDtoSchema));
        this.log = log;
    }
    async createOrUpdate(data, ttlInSeconds) {
        let currentStopTimes;
        let currentTripId;
        try {
            for (const [id, stopTimes] of data.entries()) {
                currentStopTimes = stopTimes;
                currentTripId = id;
                await this.validator.Validate(stopTimes);
            }
        }
        catch (err) {
            throw new golemio_errors_1.GeneralError(`PublicStopTimeCacheRepository: data validation failed: ${err.message}`, this.constructor.name, { ...err, stopTimes: currentStopTimes, tripId: currentTripId });
        }
        try {
            const stringifiedData = new Map();
            for (const [key, stopTimes] of data.entries()) {
                const redisKey = `${this.prefix}:${key}`;
                stringifiedData.set(redisKey, JSON.stringify(stopTimes));
            }
            const pipeline = this.connection.pipeline();
            pipeline.mset(stringifiedData);
            for (const key of stringifiedData.keys()) {
                pipeline.expire(key, ttlInSeconds);
            }
            await pipeline.exec();
        }
        catch (err) {
            throw new golemio_errors_1.GeneralError("PublicStopTimeCacheRepository: mset failed", err);
        }
    }
    async getPublicStopTimeCache(vehicleIds) {
        let stopTimeCache = [];
        try {
            stopTimeCache = await this.connection.mget(vehicleIds.map((id) => `${const_1.PUBLIC_STOP_TIME_CACHE_NAMESPACE_PREFIX}:${id}`));
        }
        catch (err) {
            throw new golemio_errors_1.GeneralError(`${this.constructor.name}: Cannot get public stop time cache from cache: ${err.message}`, this.constructor.name, err);
        }
        const results = new Map();
        for (let i = 0; i < vehicleIds.length; i++) {
            const vehicleId = vehicleIds[i];
            const cacheValue = stopTimeCache[i];
            let value;
            if (cacheValue === null) {
                this.log.info(`${this.constructor.name}: Cannot find public stop time cache with key '${vehicleId}'`);
                value = [];
            }
            else {
                try {
                    value = JSON.parse(cacheValue);
                }
                catch (err) {
                    throw new golemio_errors_1.GeneralError(`${this.constructor.name}: Cannot parse public stop time cache: ${err.message}`, this.constructor.name, err);
                }
            }
            results.set(vehicleId, value);
        }
        return results;
    }
};
exports.PublicStopTimeCacheRepository = PublicStopTimeCacheRepository;
PublicStopTimeCacheRepository.NAMESPACE_PREFIX = const_1.PUBLIC_STOP_TIME_CACHE_NAMESPACE_PREFIX;
exports.PublicStopTimeCacheRepository = PublicStopTimeCacheRepository = PublicStopTimeCacheRepository_1 = __decorate([
    (0, tsyringe_1.injectable)(),
    __param(0, (0, tsyringe_1.inject)(CoreToken_1.CoreToken.Logger)),
    __metadata("design:paramtypes", [Object])
], PublicStopTimeCacheRepository);
//# sourceMappingURL=PublicStopTimeCacheRepository.js.map