"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.DeparturePresetsFacade = void 0;
const GtfsStopParser_1 = require("../../../helpers/GtfsStopParser");
const ModuleContainerToken_1 = require("../../ioc/ModuleContainerToken");
const RopidDeparturesPresetsRopidGTFSStopsRepository_1 = require("../../jis/repositories/RopidDeparturesPresetsRopidGTFSStopsRepository");
const RopidMetadataModel_1 = require("../../shared/RopidMetadataModel");
const ContainerToken_1 = require("@golemio/core/dist/integration-engine/ioc/ContainerToken");
const tsyringe_1 = require("@golemio/core/dist/shared/tsyringe");
const RopidGTFSStopsModel_1 = require("../RopidGTFSStopsModel");
const RopidGtfsMetadataRepository_1 = require("../RopidGtfsMetadataRepository");
const DeparturePresetsRepository_1 = require("../data-access/DeparturePresetsRepository");
const DatasetEnum_1 = require("../helpers/DatasetEnum");
const RopidGtfsContainerToken_1 = require("../ioc/RopidGtfsContainerToken");
const RopidDeparturesPresetsTransformation_1 = require("../transformations/RopidDeparturesPresetsTransformation");
let DeparturePresetsFacade = class DeparturePresetsFacade {
    constructor(metadataRepository, ropidGTFSStopsModel, departurePresetsRepository, ropidDeparturesPresetsRopidGTFSStopsRepository, transformationDeparturesPresets, logger) {
        this.metadataRepository = metadataRepository;
        this.ropidGTFSStopsModel = ropidGTFSStopsModel;
        this.departurePresetsRepository = departurePresetsRepository;
        this.ropidDeparturesPresetsRopidGTFSStopsRepository = ropidDeparturesPresetsRopidGTFSStopsRepository;
        this.transformationDeparturesPresets = transformationDeparturesPresets;
        this.logger = logger;
    }
    async handleNewDeparturePresets(data, lastModified) {
        const dbLastModified = await this.metadataRepository.getLastModified(DatasetEnum_1.DatasetEnum.DEPARTURES_PRESETS);
        await this.metadataRepository.save({
            dataset: DatasetEnum_1.DatasetEnum.DEPARTURES_PRESETS,
            key: RopidMetadataModel_1.MetaDatasetInfoKeyEnum.LAST_MODIFIED,
            type: RopidMetadataModel_1.MetaTypeEnum.DATASET_INFO,
            value: lastModified,
            version: dbLastModified.version + 1,
        });
        const transformedData = await this.transformationDeparturesPresets.transform(data);
        await this.metadataRepository.save({
            dataset: DatasetEnum_1.DatasetEnum.DEPARTURES_PRESETS,
            key: "departuresPresets",
            type: RopidMetadataModel_1.MetaTypeEnum.TABLE_TOTAL_COUNT,
            value: transformedData.length,
            version: dbLastModified.version + 1,
        });
        try {
            await this.departurePresetsRepository.truncate(true);
            await this.departurePresetsRepository.save(transformedData, true);
            await this.metadataRepository.save({
                dataset: DatasetEnum_1.DatasetEnum.DEPARTURES_PRESETS,
                key: "departuresPresets",
                type: RopidMetadataModel_1.MetaTypeEnum.STATE,
                value: RopidMetadataModel_1.MetaStateEnum.SAVED,
                version: dbLastModified.version + 1,
            });
            await this.metadataRepository.checkSavedRows(DatasetEnum_1.DatasetEnum.DEPARTURES_PRESETS, dbLastModified.version + 1);
            await this.metadataRepository.replaceTmpTables(DatasetEnum_1.DatasetEnum.DEPARTURES_PRESETS, dbLastModified.version + 1);
            const mappedPresetsWithGtfsStops = await this.mapPresetsToGtfsStops();
            await this.ropidDeparturesPresetsRopidGTFSStopsRepository.refreshData(mappedPresetsWithGtfsStops);
        }
        catch (err) {
            this.logger.error(err);
            await this.metadataRepository.rollbackFailedSaving(DatasetEnum_1.DatasetEnum.DEPARTURES_PRESETS, dbLastModified.version + 1);
        }
    }
    async mapPresetsToGtfsStops() {
        const presets = await this.departurePresetsRepository.getAll();
        const mappedPresetsWithGtfsStops = [];
        for (const preset of presets) {
            const params = new URLSearchParams(preset.url_query_params);
            const aswIds = params.getAll("aswIds");
            const aswIdsWithBrackets = params.getAll("aswIds[]");
            const whereOptions = GtfsStopParser_1.GtfsStopParser.prepareAswWhereOptions([...new Set([...aswIds, ...aswIdsWithBrackets])]);
            for (const whereOption of whereOptions) {
                const stops = await this.ropidGTFSStopsModel.find({
                    where: whereOption,
                });
                if (stops.length === 0) {
                    this.logger.warn(whereOption, "cannot find gtfs stop with where options");
                    continue;
                }
                for (const stop of stops) {
                    mappedPresetsWithGtfsStops.push({ preset_id: preset.id, stop_id: stop.stop_id });
                }
            }
        }
        return mappedPresetsWithGtfsStops;
    }
};
exports.DeparturePresetsFacade = DeparturePresetsFacade;
exports.DeparturePresetsFacade = DeparturePresetsFacade = __decorate([
    (0, tsyringe_1.injectable)(),
    __param(0, (0, tsyringe_1.inject)(RopidGtfsContainerToken_1.RopidGtfsContainerToken.RopidGtfsMetadataRepository)),
    __param(1, (0, tsyringe_1.inject)(RopidGtfsContainerToken_1.RopidGtfsContainerToken.RopidGTFSStopsModel)),
    __param(2, (0, tsyringe_1.inject)(ModuleContainerToken_1.ModuleContainerToken.DeparturePresetsRepository)),
    __param(3, (0, tsyringe_1.inject)(RopidGtfsContainerToken_1.RopidGtfsContainerToken.RopidDeparturesPresetsRopidGTFSStopsRepository)),
    __param(4, (0, tsyringe_1.inject)(ModuleContainerToken_1.ModuleContainerToken.RopidDeparturesPresetsTransformation)),
    __param(5, (0, tsyringe_1.inject)(ContainerToken_1.ContainerToken.Logger)),
    __metadata("design:paramtypes", [RopidGtfsMetadataRepository_1.RopidGtfsMetadataRepository,
        RopidGTFSStopsModel_1.RopidGTFSStopsModel,
        DeparturePresetsRepository_1.DeparturePresetsRepository,
        RopidDeparturesPresetsRopidGTFSStopsRepository_1.RopidDeparturesPresetsRopidGTFSStopsRepository,
        RopidDeparturesPresetsTransformation_1.RopidDeparturesPresetsTransformation, Object])
], DeparturePresetsFacade);
//# sourceMappingURL=DeparturePresetsFacade.js.map