"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VehiclePositionsController = void 0;
const vehicle_positions_1 = require("../../schema-definitions/vehicle-positions");
const CoreToken_1 = require("@golemio/core/dist/helpers/ioc/CoreToken");
const controllers_1 = require("@golemio/core/dist/input-gateway/controllers");
const ioc_1 = require("@golemio/core/dist/input-gateway/ioc");
const golemio_errors_1 = require("@golemio/core/dist/shared/golemio-errors");
const golemio_validator_1 = require("@golemio/core/dist/shared/golemio-validator");
const DEFAULT_BATCH_SIZE = 500;
class VehiclePositionsController extends controllers_1.BaseController {
    constructor() {
        super(vehicle_positions_1.VehiclePositions.name, new golemio_validator_1.JSONSchemaValidator(vehicle_positions_1.VehiclePositions.name + "Controller", vehicle_positions_1.VehiclePositions.datasourceJsonSchema));
        /**
         * Data processing
         */
        this.processData = async (inputData) => {
            try {
                await this.validator.Validate(inputData); // throws an error
                const dataBatches = this.splitData(inputData);
                for (const batch of dataBatches) {
                    await this.sendMessageToExchange("input." + this.queuePrefix + ".saveDataToDB", JSON.stringify(batch), {
                        persistent: true,
                        timestamp: new Date().getTime(),
                    });
                }
            }
            catch (err) {
                if (err instanceof golemio_errors_1.AbstractGolemioError) {
                    throw err;
                }
                else {
                    throw new golemio_errors_1.GeneralError("Error while validating input data.", this.name, err, 422);
                }
            }
        };
        this.splitData = (data) => {
            if (!Array.isArray(data.m.spoj)) {
                return [data];
            }
            const result = [];
            for (let i = 0, chunkSize = this.batchSize; i < data.m.spoj.length; i += chunkSize) {
                const chunk = data.m.spoj.slice(i, i + chunkSize);
                result.push({ m: { spoj: chunk } });
            }
            return result;
        };
        const config = ioc_1.InputGatewayContainer.resolve(CoreToken_1.CoreToken.SimpleConfig);
        const batchSize = config.getValue("env.VEHICLE_POSITIONS_SAVE_DATA_BATCH_SIZE", DEFAULT_BATCH_SIZE.toString());
        this.batchSize = Number.parseInt(batchSize);
    }
}
exports.VehiclePositionsController = VehiclePositionsController;
//# sourceMappingURL=VehiclePositionsController.js.map