var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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 };
    }
};
var __values = (this && this.__values) || function(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
import { chunkArray } from '@iotize/common/array';
import { bufferToHexString } from '@iotize/common/byte-converter';
import { TapRequestFrame } from '@iotize/tap/client/api';
import { TapRequestFrameBuilder } from '@iotize/tap/client/impl';
import { defer, Observable } from 'rxjs';
import { first } from 'rxjs/operators';
import { PathParameter } from './path-parameter';
import { TapResponse } from './response-impl';
import { TapError } from './tap-errors';
export function serviceCallToString(call, options) {
    function printObject(obj) {
        if (obj instanceof Uint8Array) {
            return '0x' + bufferToHexString(obj);
        }
        else if (typeof obj === 'object') {
            return '{' + Object.keys(obj).map(function (key) { return "\"" + key + "\":" + printObject(obj[key]); }).join(',') + '}';
        }
        else {
            return JSON.stringify(obj);
        }
    }
    var lwm2mPath = ServiceCallRunner.resolvePathParameters(call);
    var pathAlias = call.pathAlias ? PathParameter.fillAllParams(call.pathAlias, call.pathParameters || {}) : undefined;
    var result = TapRequestFrame.MethodType[call.method] + " " + (pathAlias || lwm2mPath);
    if (call.pathAlias) {
        result += " (" + lwm2mPath + ")";
    }
    if (!(options === null || options === void 0 ? void 0 : options.skipBody) && call.body !== undefined) {
        result += ' ' + printObject(call.body);
    }
    return result;
}
var ServiceCallRunner = /** @class */ (function () {
    function ServiceCallRunner(client, options) {
        if (options === void 0) { options = {
            chunkSize: 220
        }; }
        this.client = client;
        this.options = options;
    }
    ServiceCallRunner.prototype.get = function (path, body) {
        return this.execute({
            method: TapRequestFrame.MethodType.GET,
            path: path,
            body: body
        });
    };
    ServiceCallRunner.prototype.put = function (path, body) {
        return this.execute({
            method: TapRequestFrame.MethodType.PUT,
            path: path,
            body: body
        });
    };
    ServiceCallRunner.prototype.post = function (path, body) {
        return this.execute({
            method: TapRequestFrame.MethodType.POST,
            path: path,
            body: body
        });
    };
    ServiceCallRunner.prototype.prepare = function (call) {
        var _this = this;
        return defer(function () { return __awaiter(_this, void 0, void 0, function () {
            var tapRequestFrame, tapResponseFrame, response, responseBodyDecoder, err_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        tapRequestFrame = ServiceCallRunner.toTapRequest(call);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.client.request(tapRequestFrame).toPromise()];
                    case 2:
                        tapResponseFrame = _a.sent();
                        response = new TapResponse(tapResponseFrame, tapRequestFrame);
                        responseBodyDecoder = ServiceCallRunner.resolveResponseBodyDecoder(call);
                        if (responseBodyDecoder) {
                            response.setBodyDecoder({
                                decode: responseBodyDecoder
                            });
                        }
                        if (!response.isSuccessful()) {
                            response.setError(TapError.reponseStatusError(response, call));
                        }
                        return [2 /*return*/, response];
                    case 3:
                        err_1 = _a.sent();
                        if (!(err_1 instanceof TapError)) {
                            throw TapError.executeRequestError(call, err_1);
                        }
                        throw err_1;
                    case 4: return [2 /*return*/];
                }
            });
        }); });
        // return response$.pipe(
        //     tap(
        //         response => {
        //             debug(this.constructor.name, ...debugArgs, '=>', response.toString());
        //         },
        //         err => {
        //             debug(this.constructor.name, ...debugArgs, ` => ${err.message}`);
        //         }
        //     )
        // );
    };
    ServiceCallRunner.prototype.execute = function (call) {
        return this.prepare(call).pipe(first()).toPromise();
    };
    ServiceCallRunner.prototype.createAppendCalls = function (call, chunkSize) {
        if (chunkSize === void 0) { chunkSize = this.options.chunkSize; }
        var chunks = chunkArray(Array.from(call.body || new Uint8Array()), chunkSize)
            .map(function (chunk, index) {
            return __assign(__assign({}, call), { body: Uint8Array.from(chunk) });
        });
        return chunks;
    };
    ServiceCallRunner.prototype.prepareAppendCall = function (call, chunkSize) {
        var _this = this;
        if (chunkSize === void 0) { chunkSize = this.options.chunkSize; }
        return new Observable(function (emitter) {
            var isCancelled = false;
            (function () { return __awaiter(_this, void 0, void 0, function () {
                var calls, index, byteOffset, calls_1, calls_1_1, call_1, chunk, progress, response, e_1_1, err_2;
                var e_1, _a;
                return __generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            _b.trys.push([0, 9, , 10]);
                            calls = this.createAppendCalls(call, chunkSize);
                            index = 0;
                            byteOffset = 0;
                            _b.label = 1;
                        case 1:
                            _b.trys.push([1, 6, 7, 8]);
                            calls_1 = __values(calls), calls_1_1 = calls_1.next();
                            _b.label = 2;
                        case 2:
                            if (!!calls_1_1.done) return [3 /*break*/, 5];
                            call_1 = calls_1_1.value;
                            if (isCancelled) {
                                return [2 /*return*/];
                            }
                            chunk = call_1.body;
                            progress = {
                                total: chunk.length,
                                loaded: index + 1,
                                byteOffset: byteOffset
                            };
                            emitter.next(progress);
                            return [4 /*yield*/, this.execute({
                                    method: call_1.method || TapRequestFrame.MethodType.PUT,
                                    path: call_1.path,
                                    body: chunk
                                })];
                        case 3:
                            response = _b.sent();
                            try {
                                response.successful();
                            }
                            catch (err) {
                                throw TapError.appendChunkError(err, chunk, progress);
                            }
                            byteOffset += chunk.length;
                            index++;
                            _b.label = 4;
                        case 4:
                            calls_1_1 = calls_1.next();
                            return [3 /*break*/, 2];
                        case 5: return [3 /*break*/, 8];
                        case 6:
                            e_1_1 = _b.sent();
                            e_1 = { error: e_1_1 };
                            return [3 /*break*/, 8];
                        case 7:
                            try {
                                if (calls_1_1 && !calls_1_1.done && (_a = calls_1.return)) _a.call(calls_1);
                            }
                            finally { if (e_1) throw e_1.error; }
                            return [7 /*endfinally*/];
                        case 8:
                            emitter.complete();
                            return [3 /*break*/, 10];
                        case 9:
                            err_2 = _b.sent();
                            emitter.error(err_2);
                            return [2 /*return*/];
                        case 10: return [2 /*return*/];
                    }
                });
            }); })();
            return function () {
                // TODO throw error on cancel
                isCancelled = true;
            };
        });
    };
    ServiceCallRunner.toTapRequest = function (call) {
        var path = ServiceCallRunner.resolvePathParameters(call);
        var body = ServiceCallRunner.encodeBody(call);
        return TapRequestFrameBuilder.create(call.method, path, body);
    };
    ServiceCallRunner.resolveResponseBodyDecoder = function (call) {
        if (call.responseBodyDecoder) {
            return toDecoderFunction(call.responseBodyDecoder);
        }
        return undefined;
    };
    ServiceCallRunner.resolvePathParameters = function (info) {
        return PathParameter.fillAllParams(info.path, info.pathParameters || {});
    };
    /**
     * Encode body according to options and configuration
     */
    ServiceCallRunner.encodeBody = function (options) {
        if (options.body === undefined) {
            return undefined;
        }
        var encoded = options.bodyEncoder
            ? toEncoderFunction(options.bodyEncoder)(options.body)
            : options.body;
        if (encoded !== undefined && !(encoded instanceof Uint8Array)) {
            throw TapError.invalidServiceCallConfiguration("Request body encoder is required for call to " + serviceCallToString(options));
        }
        return encoded;
    };
    return ServiceCallRunner;
}());
export { ServiceCallRunner };
function toEncoderFunction(classOrFunction) {
    return typeof classOrFunction === 'function' ? classOrFunction : classOrFunction.encode.bind(classOrFunction);
}
function toDecoderFunction(classOrFunction) {
    return typeof classOrFunction === 'function' ? classOrFunction : classOrFunction.decode.bind(classOrFunction);
}
//# sourceMappingURL=data:application/json;base64, 