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());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { ServiceCallRunner, TapError, TapResponse } from '@iotize/tap';
import { MultiRequestFrame } from '../generated/models';
import { InterfaceService } from '../generated/service';
// type ExecuteMultipleCallsParameterType<BodyType, ReturnType> = ExecuteMutlipleCallItem<>[];
var 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) {
    if (defaultExpectedResponseStatus === void 0) { defaultExpectedResponseStatus = MultiRequestFrame.ExpectedResponseStatus.ANYTHING; }
    return __awaiter(this, void 0, void 0, function () {
        var decoders, multiRequestRequests, multiRequestFrame, response, body, responses;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    decoders = calls.map(function (serviceCall) { return toBodyDecoder(toCall(serviceCall).responseBodyDecoder); });
                    multiRequestRequests = createMultiRequestItems(calls, defaultExpectedResponseStatus);
                    multiRequestFrame = {
                        requests: multiRequestRequests.map(function (item) { return item.requestItem; })
                    };
                    return [4 /*yield*/, this.executeMultiRequestFrame(multiRequestFrame)];
                case 1:
                    response = _a.sent();
                    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).");
                    }
                    responses = body.responses.map(function (tapResponseItem, index) {
                        var response = new TapResponse(tapResponseItem.response);
                        var 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 [2 /*return*/, responses];
            }
        });
    });
};
export function createMultiRequestItems(calls, defaultExpectedResponseStatus) {
    if (defaultExpectedResponseStatus === void 0) { defaultExpectedResponseStatus = MultiRequestFrame.ExpectedResponseStatus.ANYTHING; }
    return calls.map(function (serviceCall) {
        var call;
        var expectedResponseStatus;
        if ('expectedResponseStatus' in serviceCall) {
            call = serviceCall.call;
            expectedResponseStatus = serviceCall.expectedResponseStatus;
        }
        else {
            call = serviceCall;
            expectedResponseStatus = defaultExpectedResponseStatus;
        }
        var request = ServiceCallRunner.toTapRequest(call);
        var responseBodyDecoder = ServiceCallRunner.resolveResponseBodyDecoder(call);
        return {
            requestItem: {
                expectedResponseStatus: expectedResponseStatus,
                request: request,
                requestLen: request.payload.length +
                    TAP_REQUEST_FRAME_HEADER_LENGTH
            },
            responseBodyDecoder: responseBodyDecoder
        };
    });
}
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXVsdGktcmVxdWVzdC1pbnRlcmZhY2Utc2VydmljZS1leHRlbnNpb24uanMiLCJzb3VyY2VSb290Ijoibmc6Ly9AaW90aXplL3RhcC9zZXJ2aWNlL2ltcGwvaW50ZXJmYWNlLyIsInNvdXJjZXMiOlsibGliL2N1c3RvbS9tdWx0aS1yZXF1ZXN0LWludGVyZmFjZS1zZXJ2aWNlLWV4dGVuc2lvbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFDQSxPQUFPLEVBQUUsaUJBQWlCLEVBQW1CLFFBQVEsRUFBRSxXQUFXLEVBQUUsTUFBTSxhQUFhLENBQUM7QUFHeEYsT0FBTyxFQUFFLGlCQUFpQixFQUFzQixNQUFNLHFCQUFxQixDQUFDO0FBQzVFLE9BQU8sRUFBRSxnQkFBZ0IsRUFBRSxNQUFNLHNCQUFzQixDQUFDO0FBTXhELDhGQUE4RjtBQUU5RixJQUFNLCtCQUErQixHQUFHLENBQUMsQ0FBQyxDQUFDLHlCQUF5QjtBQXNEcEUsU0FBUyxhQUFhLENBQVUsS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