"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.JISEventsDataService = void 0;
const JISContainerToken_1 = require("../ioc/JISContainerToken");
const JISEventsRepository_1 = require("../repositories/JISEventsRepository");
const JISEventsRopidGTFSRoutesRepository_1 = require("../repositories/JISEventsRopidGTFSRoutesRepository");
const CoreToken_1 = require("@golemio/core/dist/helpers/ioc/CoreToken");
const golemio_errors_1 = require("@golemio/core/dist/shared/golemio-errors");
const tsyringe_1 = require("@golemio/core/dist/shared/tsyringe");
let JISEventsDataService = class JISEventsDataService {
    constructor(eventsRepository, eventsRopidGTFSRoutesRepository, databaseConnector, logger) {
        this.eventsRepository = eventsRepository;
        this.eventsRopidGTFSRoutesRepository = eventsRopidGTFSRoutesRepository;
        this.databaseConnector = databaseConnector;
        this.logger = logger;
        // do nothing
    }
    /**
     * Refresh all JIS event data by inserting or updating the given events and their ROPID-GTFS routes.
     * Existing records are preserved and only incoming events/routes are upserted.
     *
     * @param events               Array of JIS events to insert or update.
     * @param eventsRopidGTFSRoutes Array of corresponding ROPID-GTFS route records to insert or update.
     * @returns boolean true if any events were saved, false if no events were saved.
     */
    async upsertAll(events, eventsRopidGTFSRoutes) {
        const connection = this.databaseConnector.getConnection();
        const transaction = await connection.transaction();
        const saveTime = new Date();
        try {
            if (events.length === 0) {
                this.logger.info(`${this.constructor.name}.upsertAll: 0 events were imported - keeping existing data`);
                await transaction.commit();
                return false;
            }
            else {
                const isSingleUpdate = events.length === 1;
                const savedEvents = await this.eventsRepository.upsertAll(events, { transaction });
                await this.eventsRopidGTFSRoutesRepository.upsertAll(eventsRopidGTFSRoutes, { transaction });
                await this.eventsRopidGTFSRoutesRepository.deleteAllLastUpdatedBefore(saveTime, events, {
                    transaction,
                });
                await transaction.commit();
                this.logger.info(`${this.constructor.name}.upsertAll: ${events.length} JIS events and ` +
                    `${eventsRopidGTFSRoutes.length} JIS eventsRopidGTFSRoutes were saved ` +
                    (isSingleUpdate ? "(single update)" : "(full sync)"));
                if (savedEvents.length === 0) {
                    return false;
                }
                return true;
            }
        }
        catch (err) {
            await transaction.rollback();
            if (err instanceof golemio_errors_1.GeneralError)
                throw err;
            throw new golemio_errors_1.GeneralError("Refreshing JIS Events in database failed", this.constructor.name, err);
        }
    }
};
exports.JISEventsDataService = JISEventsDataService;
exports.JISEventsDataService = JISEventsDataService = __decorate([
    (0, tsyringe_1.injectable)(),
    __param(0, (0, tsyringe_1.inject)(JISContainerToken_1.JISContainerToken.JISEventsRepository)),
    __param(1, (0, tsyringe_1.inject)(JISContainerToken_1.JISContainerToken.JISEventsRopidGTFSRoutesRepository)),
    __param(2, (0, tsyringe_1.inject)(CoreToken_1.CoreToken.PostgresConnector)),
    __param(3, (0, tsyringe_1.inject)(CoreToken_1.CoreToken.Logger)),
    __metadata("design:paramtypes", [JISEventsRepository_1.JISEventsRepository,
        JISEventsRopidGTFSRoutesRepository_1.JISEventsRopidGTFSRoutesRepository, Object, Object])
], JISEventsDataService);
//# sourceMappingURL=JISEventsDataService.js.map