"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.UIBatchError = void 0;
exports.getBatchError = getBatchError;
exports.splitBatchResults = splitBatchResults;
const forEach_1 = __importDefault(require("lodash/forEach"));
class UIBatchError {
    constructor(error) {
        this.message = '';
        delete this.code;
        delete this.attributes;
        delete this.inner_errors;
        if (typeof error === 'string') {
            this.message = error;
        }
        else {
            Object.assign(this, error);
        }
    }
}
exports.UIBatchError = UIBatchError;
function getBatchError(batchResults, message) {
    return splitBatchResults(batchResults, new UIBatchError(message)).error;
}
function splitBatchResults(batchResults, inputError, { ignoreErrorCodes } = {}) {
    const dstError = typeof inputError === 'string' ? new UIBatchError(inputError) : inputError;
    const ignoreCodes = new Set(ignoreErrorCodes);
    const errorIgnoredIndices = [];
    const innerErrors = [];
    const results = [];
    const outputs = [];
    const errorIndices = [];
    const resultIndices = [];
    (0, forEach_1.default)(batchResults, (res, index) => {
        const { error, output } = res;
        outputs.push(output);
        if (error) {
            if (ignoreCodes.has(error.code)) {
                errorIgnoredIndices.push(index);
            }
            else {
                innerErrors.push(error);
                errorIndices.push(index);
            }
        }
        else {
            results.push(output);
            resultIndices.push(index);
        }
    });
    if (innerErrors.length) {
        dstError.inner_errors = dstError.inner_errors ?? [];
        dstError.inner_errors.push(...innerErrors);
    }
    const error = !innerErrors.length ? undefined : dstError;
    return {
        error: error,
        results,
        outputs,
        errorIndices,
        resultIndices,
        errorIgnoredIndices,
    };
}
