"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.CollectAndSaveLogsTask = void 0;
const ModuleContainerToken_1 = require("../../../../ioc/ModuleContainerToken");
const CoreToken_1 = require("@golemio/core/dist/helpers/ioc/CoreToken");
const queueprocessors_1 = require("@golemio/core/dist/integration-engine/queueprocessors");
const workers_1 = require("@golemio/core/dist/integration-engine/workers");
const golemio_errors_1 = require("@golemio/core/dist/shared/golemio-errors");
const tsyringe_1 = require("@golemio/core/dist/shared/tsyringe");
const PresetLogProviderEnum_1 = require("../datasources/helpers/PresetLogProviderEnum");
const LogQueryManager_1 = require("../helpers/LogQueryManager");
const LogCollectionSchema_1 = require("../schema/LogCollectionSchema");
const constants_1 = require("../constants");
let CollectAndSaveLogsTask = class CollectAndSaveLogsTask extends workers_1.AbstractTask {
    constructor(dataSourceFactory, logTransformation, logRepository, logFilter, logger) {
        super(constants_1.PRESETS_WORKER_NAME);
        this.dataSourceFactory = dataSourceFactory;
        this.logTransformation = logTransformation;
        this.logRepository = logRepository;
        this.logFilter = logFilter;
        this.logger = logger;
        this.queueName = "collectAndSaveLogs";
        this.queueTtl = 59 * 1000; // 59 seconds
        this.schema = LogCollectionSchema_1.LogCollectionValidationSchema;
    }
    async execute(data) {
        const currentTimestampInSeconds = Math.round(new Date().getTime() / 1000);
        const dataSource = this.dataSourceFactory.getDataSource(PresetLogProviderEnum_1.PresetLogProvider.GrafanaLoki, {
            start: currentTimestampInSeconds - data.targetMinutes * 60,
            end: currentTimestampInSeconds,
            query: LogQueryManager_1.LogQueryManager.getCompletedPresetRequestLogsQuery(),
        });
        let queryResult = [];
        try {
            queryResult = await dataSource.getAll();
        }
        catch (err) {
            if (err instanceof golemio_errors_1.AbstractGolemioError) {
                throw err;
            }
            throw new golemio_errors_1.DatasourceError("Error while fetching preset logs", this.constructor.name, err);
        }
        const validLogEntries = this.logFilter.getValidLogEntries(queryResult);
        if (validLogEntries.length > 0) {
            const presetLogDtos = this.logTransformation.transformArray(queryResult);
            this.logger.info(`${this.constructor.name}: ${presetLogDtos.length} log entries collected`);
            await this.logRepository.saveData(presetLogDtos);
        }
        else {
            this.logger.warn(`${this.constructor.name}: no valid log entries collected`);
        }
        await queueprocessors_1.QueueManager.sendMessageToExchange(this.queuePrefix, "processAndSendLogs", {});
    }
};
exports.CollectAndSaveLogsTask = CollectAndSaveLogsTask;
exports.CollectAndSaveLogsTask = CollectAndSaveLogsTask = __decorate([
    (0, tsyringe_1.injectable)(),
    __param(0, (0, tsyringe_1.inject)(ModuleContainerToken_1.ModuleContainerToken.PresetLogDataSourceFactory)),
    __param(1, (0, tsyringe_1.inject)(ModuleContainerToken_1.ModuleContainerToken.PresetLogTransformation)),
    __param(2, (0, tsyringe_1.inject)(ModuleContainerToken_1.ModuleContainerToken.PresetLogRepository)),
    __param(3, (0, tsyringe_1.inject)(ModuleContainerToken_1.ModuleContainerToken.PresetLogFilter)),
    __param(4, (0, tsyringe_1.inject)(CoreToken_1.CoreToken.Logger)),
    __metadata("design:paramtypes", [Object, Object, Object, Object, Object])
], CollectAndSaveLogsTask);
//# sourceMappingURL=CollectAndSaveLogsTask.js.map