var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { ServiceCallRunner, TapError, TapResponse } from '@iotize/tap';
import { MultiRequestFrame } from '../generated/models';
import { InterfaceService } from '../generated/service';
// type ExecuteMultipleCallsParameterType<BodyType, ReturnType> = ExecuteMutlipleCallItem<>[];
const TAP_REQUEST_FRAME_HEADER_LENGTH = 7; // TODO generated instead
function toBodyDecoder(input) {
    if (typeof input === 'function') {
        return {
            decode: input
        };
    }
    else {
        return input;
    }
}
function toCall(serviceCall) {
    if ('expectedResponseStatus' in serviceCall) {
        return serviceCall.call;
    }
    else {
        return serviceCall;
    }
}
InterfaceService.prototype.executeMultipleCalls = function (calls, defaultExpectedResponseStatus = MultiRequestFrame.ExpectedResponseStatus.ANYTHING) {
    return __awaiter(this, void 0, void 0, function* () {
        const decoders = calls.map(serviceCall => toBodyDecoder(toCall(serviceCall).responseBodyDecoder));
        const multiRequestRequests = createMultiRequestItems(calls, defaultExpectedResponseStatus);
        const multiRequestFrame = {
            requests: multiRequestRequests.map(item => item.requestItem)
        };
        const response = yield this.executeMultiRequestFrame(multiRequestFrame);
        const body = response.body();
        if (body.responses.length !== calls.length) {
            throw new Error(`API sent ${calls.length} request(s) but tap responded with ${body.responses.length} response(s).`);
        }
        const responses = body.responses.map((tapResponseItem, index) => {
            const response = new TapResponse(tapResponseItem.response);
            const decoder = decoders[index];
            if (decoder) {
                response.setBodyDecoder(decoder);
            }
            response.setRequest(multiRequestRequests[index].requestItem.request);
            if (!response.isSuccessful()) {
                response.setError(TapError.reponseStatusError(response, toCall(calls[index])));
            }
            return response;
        });
        return responses;
    });
};
export function createMultiRequestItems(calls, defaultExpectedResponseStatus = MultiRequestFrame.ExpectedResponseStatus.ANYTHING) {
    return calls.map((serviceCall) => {
        let call;
        let expectedResponseStatus;
        if ('expectedResponseStatus' in serviceCall) {
            call = serviceCall.call;
            expectedResponseStatus = serviceCall.expectedResponseStatus;
        }
        else {
            call = serviceCall;
            expectedResponseStatus = defaultExpectedResponseStatus;
        }
        const request = ServiceCallRunner.toTapRequest(call);
        const responseBodyDecoder = ServiceCallRunner.resolveResponseBodyDecoder(call);
        return {
            requestItem: {
                expectedResponseStatus,
                request,
                requestLen: request.payload.length +
                    TAP_REQUEST_FRAME_HEADER_LENGTH
            },
            responseBodyDecoder
        };
    });
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXVsdGktcmVxdWVzdC1pbnRlcmZhY2Utc2VydmljZS1leHRlbnNpb24uanMiLCJzb3VyY2VSb290Ijoibmc6Ly9AaW90aXplL3RhcC9zZXJ2aWNlL2ltcGwvaW50ZXJmYWNlLyIsInNvdXJjZXMiOlsibGliL2N1c3RvbS9tdWx0aS1yZXF1ZXN0LWludGVyZmFjZS1zZXJ2aWNlLWV4dGVuc2lvbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7QUFDQSxPQUFPLEVBQUUsaUJBQWlCLEVBQW1CLFFBQVEsRUFBRSxXQUFXLEVBQUUsTUFBTSxhQUFhLENBQUM7QUFHeEYsT0FBTyxFQUFFLGlCQUFpQixFQUFzQixNQUFNLHFCQUFxQixDQUFDO0FBQzVFLE9BQU8sRUFBRSxnQkFBZ0IsRUFBRSxNQUFNLHNCQUFzQixDQUFDO0FBTXhELDhGQUE4RjtBQUU5RixNQUFNLCtCQUErQixHQUFHLENBQUMsQ0FBQyxDQUFDLHlCQUF5QjtBQXNEcEUsU0FBUyxhQUFhLENBQVUsS0FBNkQ7SUFDekYsSUFBSSxPQU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