"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
 * @module RpcInterface
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.createMultipartStream = createMultipartStream;
exports.parseMultipartRequest = parseMultipartRequest;
exports.appendToMultipartForm = appendToMultipartForm;
const core_bentley_1 = require("@itwin/core-bentley");
const core_common_1 = require("@itwin/core-common");
const FormData = require("form-data");
const multiparty = require("multiparty");
/* eslint-disable @typescript-eslint/no-deprecated */
/** @internal */
function createMultipartStream(value) {
    const form = new FormData();
    core_common_1.RpcMultipart.writeValueToForm(form, value);
    // Type information for FormData is lying. It actually extends Stream but not Readable, although it appears to work
    // fine for now.
    return form;
}
/** @internal */
async function parseMultipartRequest(req) {
    return new Promise((resolve, reject) => {
        const form = new multiparty.Form({ maxFieldsSize: Infinity });
        form.on("error", (err) => {
            reject(err);
        });
        const value = core_common_1.RpcSerializedValue.create();
        const data = {};
        form.on("part", (part) => {
            part.on("data", (chunk) => {
                if (part.name === "objects") {
                    value.objects += chunk.toString();
                }
                else if (Buffer.isBuffer(chunk)) {
                    if (!data[part.name]) {
                        data[part.name] = { size: 0, chunks: [] };
                    }
                    data[part.name].size += chunk.byteLength;
                    data[part.name].chunks.push(chunk);
                }
                else {
                    throw new core_common_1.IModelError(core_bentley_1.BentleyStatus.ERROR, "Unknown input.");
                }
            });
        });
        form.on("close", () => {
            let i = 0;
            for (;;) {
                const part = data[`data-${i}`];
                if (!part) {
                    break;
                }
                value.data.push(Buffer.concat(part.chunks, part.size));
                ++i;
            }
            resolve(value);
        });
        form.parse(req);
    });
}
/** @internal */
function appendToMultipartForm(i, form, value) {
    const buf = value.data[i];
    form.append(`data-${i}`, Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength));
}
//# sourceMappingURL=multipart.js.map