import { TapRequestFrame, ResultCode, ApduResponse } from '@iotize/tap/client/api';
import { tapResponseStatusToString, TapResponseFrameBuilder, TapRequestFrameBuilder, TapClient, NumberConverter, TapStreamReader, TapStreamWriter } from '@iotize/tap/client/impl';
import { defer, Observable, Subject } from 'rxjs';
import { createLazyDebugger, createDebugger } from '@iotize/common/debug';
import { chunkArray } from '@iotize/common/array';
import { bufferToHexString } from '@iotize/common/byte-converter';
import { first } from 'rxjs/operators';
import { CodeError } from '@iotize/common/error';

var PathParameter = /** @class */ (function () {
    function PathParameter() {
    }
    PathParameter.fillParam = function (path, key, value) {
        var map = {};
        map[key] = value;
        return PathParameter.fillParams(path, map);
    };
    /**
     * Same as fillParams but will throw an error if some parameters has not been replaced
     */
    PathParameter.fillAllParams = function (path, pathParameters) {
        path = PathParameter.fillParams(path, pathParameters);
        var remainingArgs = PathParameter.extractParams(path);
        if (remainingArgs.length > 0) {
            throw new Error("Missing path parameter " + remainingArgs.join(', ') + " (path: " + path + ")");
        }
        return path;
    };
    PathParameter.fillParams = function (path, mapping) {
        for (var key in mapping) {
            var match = '{' + key + '}';
            if (path.indexOf(match) >= 0) {
                path = path.replace(match, mapping[key].toString());
            }
            else {
                throw new Error('Parameter ' + key + ' does not exist in path: ' + path);
            }
        }
        return path;
    };
    /**
     *
     * @param path
     * @returns names of path parameters
     */
    PathParameter.extractParams = function (path) {
        var found = [], rxp = PathParameter.PARAMETER_REGEX, curMatch;
        while ((curMatch = rxp.exec(path))) {
            found.push(curMatch[1]);
        }
        return found;
    };
    PathParameter.hasParams = function (path) {
        return PathParameter.extractParams(path).length > 0;
    };
    return PathParameter;
}());
(function (PathParameter) {
    PathParameter.PARAMETER_REGEX = /{([^}]+)}/g;
})(PathParameter || (PathParameter = {}));

var prefix = '@iotize/tap';
var lazyDebug = createLazyDebugger(prefix);
var debug = createDebugger(prefix);

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var TapError = /** @class */ (function (_super) {
    __extends(TapError, _super);
    function TapError(code, message, cause) {
        var _this = _super.call(this, message, code) || this;
        _this.cause = cause;
        return _this;
    }
    TapError.cannotStartScram = function (err) {
        return new TapError(TapError.Code.CannotStartScram, "Cannot start encrypted session, initialization failed. Cause: " + err.message, err);
    };
    TapError.notImplementedYet = function (msg) {
        throw new TapError(TapError.Code.NotImplemented, msg);
    };
    TapError.initializationVectorNotSupported = function (err) {
        return new TapError(TapError.Code.InitializationVectorNotSupported, "Initialization vector for SCRAM is not implemented with your current firmware version. You cannot use this feature.", err);
    };
    TapError.executeRequestError = function (request, err) {
        return new TapError(TapError.Code.ExecuteRequestError, "Tap request " + TapRequestFrame.MethodType[request.method] + " " + (request.pathAlias || request.path) + " failed. " + err.message, err);
    };
    TapError.reponseStatusError = function (response, call) {
        return new TapResponseStatusError(response, call);
    };
    TapError.invalidServiceCallConfiguration = function (msg) {
        return new TapError(TapError.Code.InvalidServiceCallConfiguration, msg);
    };
    TapError.appendChunkError = function (cause, chunk, progress) {
        return new AppendChunkError(cause, chunk, progress);
    };
    TapError.nfcPairingError = function (msg, cause) {
        return new TapError(TapError.Code.NfcPairingError, "NFC pairing failed. " + msg, cause);
    };
    return TapError;
}(CodeError));
(function (TapError) {
    var Code;
    (function (Code) {
        Code["CannotStartScram"] = "TapErrorCannotStartScram";
        Code["NotImplemented"] = "TapErrorNotImplemented";
        Code["InitializationVectorNotSupported"] = "TapErrorInitializationVectorNotSupported";
        Code["AppendChunkError"] = "AppendChunkError";
        Code["ResponseStatusError"] = "TapErrorTapResponseStatusError";
        Code["InvalidServiceCallConfiguration"] = "TapErrorInvalidServiceCallConfiguration";
        Code["ExecuteRequestError"] = "TapErrorTapExecuteRequestError";
        Code["NfcPairingError"] = "TapErrorNfcPairingError";
    })(Code = TapError.Code || (TapError.Code = {}));
})(TapError || (TapError = {}));
var TapResponseStatusError = /** @class */ (function (_super) {
    __extends(TapResponseStatusError, _super);
    function TapResponseStatusError(response, call) {
        var _this = _super.call(this, TapError.Code.ResponseStatusError, "Tap request " + (call ? serviceCallToString(call) + " " : (response.request ? response.request.toString() + ' ' : '')) + "failed. " + tapResponseStatusToString(response.status) + " (status code 0x" + response.status.toString(16) + ")") || this;
        _this.response = response;
        return _this;
    }
    return TapResponseStatusError;
}(TapError));
var AppendChunkError = /** @class */ (function (_super) {
    __extends(AppendChunkError, _super);
    function AppendChunkError(cause, chunk, progress) {
        var _this = _super.call(this, TapError.Code.AppendChunkError, "Appending data chunk n\u00B0" + progress.loaded + "/" + progress.total + " failed with error: " + cause.message, cause) || this;
        _this.chunk = chunk;
        _this.progress = progress;
        return _this;
    }
    return AppendChunkError;
}(TapError));

var TapResponse = /** @class */ (function () {
    function TapResponse(_tapResponse, request, bodyDecoder) {
        this._tapResponse = _tapResponse;
        this.request = request;
        this.bodyDecoder = bodyDecoder;
    }
    TapResponse.SUCCESS = function (data) {
        return TapResponse.create(ResultCode.OK, data);
    };
    TapResponse.ERROR = function (errorCode) {
        errorCode = errorCode || ResultCode.BAD_REQUEST;
        return TapResponse.create(errorCode);
    };
    TapResponse.create = function (codeRet, data) {
        return new TapResponse(TapResponseFrameBuilder.create(codeRet, data));
    };
    Object.defineProperty(TapResponse.prototype, "data", {
        get: function () {
            return this._tapResponse.data;
        },
        enumerable: true,
        configurable: true
    });
    TapResponse.prototype.body = function (decoder) {
        this.successful();
        if (decoder) {
            return decoder.decode(this.rawBody());
        }
        else if (this._bodyCache === undefined) {
            if (this.bodyDecoder) {
                this._bodyCache = this.bodyDecoder.decode(this.rawBody());
            }
            else {
                this._bodyCache = this.rawBody();
            }
        }
        // In this case we now that T = DataType
        return this._bodyCache;
    };
    TapResponse.prototype.rawBody = function () {
        if (this.data) {
            return this.data;
        }
        else {
            return new Uint8Array(0);
        }
    };
    TapResponse.prototype.setBodyDecoder = function (decoder) {
        this.bodyDecoder = decoder;
        return this;
    };
    TapResponse.prototype.hasBody = function () {
        return this.rawBody() != null;
    };
    TapResponse.prototype.codeRet = function () {
        return this.status;
    };
    Object.defineProperty(TapResponse.prototype, "status", {
        get: function () {
            return this._tapResponse.status;
        },
        enumerable: true,
        configurable: true
    });
    TapResponse.prototype.toString = function () {
        return "ResponseMessage[codeRet=\"" + this.status + "\";data=\"" + (this.hasBody()
            ? bufferToHexString(this.rawBody())
            : 'NO DATA') + "\";decoder=" + (this.bodyDecoder ? this.bodyDecoder.constructor.name : 'NONE') + "]";
    };
    TapResponse.prototype.toBytes = function () {
        return this.data;
    };
    TapResponse.prototype.setBody = function (body) {
        this._bodyCache = body;
    };
    TapResponse.prototype.isSuccessful = function () {
        return (this.status & 0x80) === 0;
    };
    TapResponse.prototype.setError = function (err) {
        return this.error = err;
    };
    TapResponse.prototype.successful = function () {
        if (!this.isSuccessful()) {
            if (this.error) {
                throw this.error;
            }
            else {
                throw TapError.reponseStatusError(this);
            }
        }
    };
    TapResponse.prototype.setRequest = function (request) {
        this.request = request;
    };
    return TapResponse;
}());

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.");
};
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;
}());
function toEncoderFunction(classOrFunction) {
    return typeof classOrFunction === 'function' ? classOrFunction : classOrFunction.encode.bind(classOrFunction);
}
function toDecoderFunction(classOrFunction) {
    return typeof classOrFunction === 'function' ? classOrFunction : classOrFunction.decode.bind(classOrFunction);
}

var AbstractService = /** @class */ (function () {
    function AbstractService(serviceCallRunner) {
        this.serviceCallRunner = serviceCallRunner;
    }
    return AbstractService;
}());

var __read = (this && this.__read) || function (o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
};
var __spread = (this && this.__spread) || function () {
    for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
    return ar;
};
/**
 * This class will be augmented when importing specific service
 * For example:
 * ```typescript
 * const container: ServiceContainer;
 * expect(container.interface).to.be.undefined;
 * import '@iotize/tap/service/interface';
 * expect(container.interface).to.be.not.undefined;
 *
 * ```
 */
var ServiceContainer = /** @class */ (function () {
    function ServiceContainer(serviceCallRunner) {
        this.serviceCallRunner = serviceCallRunner;
    }
    /**
     * List loaded services
     */
    ServiceContainer.prototype.services = function () {
        return Object.values(this.servicesMap());
    };
    ServiceContainer.prototype.servicesMap = function () {
        var services = {};
        for (var key in this) {
            var hasDescriptor = Object.getOwnPropertyDescriptor(ServiceContainer.prototype, key);
            var value = this[key];
            if (hasDescriptor === null || hasDescriptor === void 0 ? void 0 : hasDescriptor.enumerable) {
                if (value instanceof AbstractService) {
                    services[key] = value;
                }
            }
        }
        return services;
    };
    /**
     * List all loaded resources
     */
    ServiceContainer.prototype.resources = function () {
        return this
            .services()
            .reduce(function (prev, service) {
            prev.push.apply(prev, __spread(Object.values(service.resources)));
            return prev;
        }, []);
    };
    return ServiceContainer;
}());
function extendServiceContainer(attrName, serviceConstructor) {
    var hiddenAttrName = "__" + attrName + "__";
    Object.defineProperty(ServiceContainer.prototype, hiddenAttrName, {
        enumerable: false,
        configurable: true,
        writable: true,
        value: undefined
    });
    return Object.defineProperty(ServiceContainer.prototype, attrName, {
        get: function () {
            var that = this;
            if (!that[hiddenAttrName]) {
                that[hiddenAttrName] = new serviceConstructor(this.serviceCallRunner);
            }
            return that[hiddenAttrName];
        },
        enumerable: true,
        configurable: true
    });
}

var NFC_PAIRING_COMMAND = Uint8Array.from([
    0x00,
    0xa4,
    0x04,
    0x00,
    0x07,
    // DATA
    0xf0,
    0x02,
    0x4c,
    0x77,
    0x4d,
    0x32,
    0x4d,
    // --
    0x90,
    0x00 // SW2
]);
var DEFAULT_TAP_MAX_FRAME_SIZE = 256 - 6; // Lc = u8 legnth - 5 header bytes  - 1 byte "Le"

var __awaiter$1 = (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$1 = (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 TAG = 'Device';
/**
 *
 */
var Tap = /** @class */ (function () {
    function Tap(client) {
        this._events = new Subject();
        this._client = client;
        this._lwm2m = new ServiceCallRunner(this.client);
        this.service = new ServiceContainer(this._lwm2m);
        // 'service', (context) => new ServiceContainer(context.tap.lwm2m)
        // this._scramInterceptor = new ScramInterceptor(
        //     this._services.scram,
        //     this.apiConfig
        // );
        // this._client.addInterceptor(this._scramInterceptor);
        // this._initCache();
        // this._converterProvider = new ConverterProvider(PathToTypeMap, DefaultConverterMap);
    }
    Object.defineProperty(Tap.prototype, "events", {
        get: function () {
            return this._events.asObservable();
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Tap.prototype, "client", {
        get: function () {
            return this._client;
        },
        set: function (client) {
            this._client = client;
            this._lwm2m.client = client;
            // this._services.client = client;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Tap.prototype, "lwm2m", {
        get: function () {
            return this._lwm2m;
        },
        enumerable: true,
        configurable: true
    });
    Tap.prototype.notifyEvent = function (event) {
        this._events.next(event);
    };
    Tap.create = function () {
        return new Tap(TapClient.create());
    };
    Tap.fromProtocol = function (protocol) {
        var client = TapClient.create();
        client.addComProtocol(protocol);
        return new Tap(client);
    };
    Object.defineProperty(Tap.prototype, "protocol", {
        get: function () {
            return this.client.getCurrentProtocol();
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Connect with the given communication protocol
     * TODO what if there is already a connected communication protocol
     * @param protocol
     */
    Tap.prototype.connect = function (protocol) {
        debug(TAG, 'connecting...');
        // this._clearCache();
        if (protocol) {
            this.client.addComProtocol(protocol, 'default');
        }
        return this._client.connect().toPromise();
    };
    /**
     * Disconnect device
     */
    Tap.prototype.disconnect = function () {
        debug(TAG, 'disconnecting...');
        // if (options.clearCache) {
        //     this.clearCache();
        // }
        // if (options.clearSession) {
        //     this.clearSession();
        // }
        return this._client.disconnect().toPromise();
    };
    Tap.prototype.isConnected = function () {
        if (!this._client) {
            return false;
        }
        return this._client.isConnected();
    };
    /**
     * Configure current tap instance thanks to a TapConfigurator
     * @param configurator
     */
    Tap.prototype.configure = function (configurator) {
        return configurator.configure(this).toPromise();
    };
    /**
     *
     * @param protocol
     */
    Tap.prototype.useComProtocol = function (protocol) {
        this.client.useComProtocol(protocol);
        return this;
    };
    /**
     * Send an NFC pairing request
     */
    Tap.prototype.nfcPairing = function () {
        return __awaiter$1(this, void 0, void 0, function () {
            var comProtocol, response, statusCode;
            return __generator$1(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.client.getCurrentProtocol()];
                    case 1:
                        comProtocol = _a.sent();
                        return [4 /*yield*/, comProtocol.send(NFC_PAIRING_COMMAND).toPromise()];
                    case 2:
                        response = _a.sent();
                        if (response.length !== 2) {
                            throw TapError.nfcPairingError("Tap responded with a frame size of " + response.length + " byte(s) but expecting 2 bytes.");
                        }
                        statusCode = NumberConverter.uint16().decode(response);
                        if (statusCode !== ApduResponse.Status.OK) {
                            throw TapError.nfcPairingError("Tap responded with an invalid APDU response status 0x" + statusCode.toString(16) + ".");
                        }
                        return [2 /*return*/, response];
                }
            });
        });
    };
    Tap.TAG = 'Tap';
    return Tap;
}());

var __awaiter$2 = (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$2 = (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 };
    }
};
/**
 * If response status code is NOT_IMPLEMENTED or NOT_FOUND it will returns the default value
 * @param responsePromise
 * @param defaultValue
 */
function defaultValueIfTapRequetNotImplemented(responsePromise, defaultValue) {
    return __awaiter$2(this, void 0, void 0, function () {
        var response;
        return __generator$2(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, responsePromise];
                case 1:
                    response = _a.sent();
                    if (!response.isSuccessful()) {
                        if (response.status === ResultCode.NOT_IMPLEMENTED
                            || response.status === ResultCode.NOT_FOUND) {
                            return [2 /*return*/, defaultValue];
                        }
                    }
                    return [2 /*return*/, response.body()];
            }
        });
    });
}
/**
 * Utility function add a new getter to the Tap prototype
 */
function defineTapPropertyExtension(propName, factory) {
    Object.defineProperty(Tap.prototype, propName, {
        get: function () {
            var that = this;
            var hiddentPropName = "__" + propName + "__";
            if (!that[hiddentPropName]) {
                that[hiddentPropName] = factory({
                    tap: this
                });
            }
            return that[hiddentPropName];
        },
        enumerable: false,
        configurable: true
    });
}

/* tslint:disable */
/**
 * This file was automatically generated by json-schema-to-typescript.
 * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
 * and run json-schema-to-typescript to regenerate this file.
 */
var HostProtocol;
(function (HostProtocol) {
    HostProtocol[HostProtocol["NFC"] = 1] = "NFC";
    HostProtocol[HostProtocol["BLUETOOTH"] = 2] = "BLUETOOTH";
    HostProtocol[HostProtocol["GSM"] = 4] = "GSM";
    HostProtocol[HostProtocol["USB_RLINK"] = 8] = "USB_RLINK";
    HostProtocol[HostProtocol["USB_CMISIS_DAP"] = 16] = "USB_CMISIS_DAP";
    HostProtocol[HostProtocol["WIFI"] = 32] = "WIFI";
    HostProtocol[HostProtocol["BLE"] = 64] = "BLE";
    HostProtocol[HostProtocol["UART"] = 256] = "UART";
    HostProtocol[HostProtocol["MQTT"] = 512] = "MQTT";
    HostProtocol[HostProtocol["WEBSOCKET"] = 1024] = "WEBSOCKET";
})(HostProtocol || (HostProtocol = {}));
/* tslint:disable */
/**
 * This file was automatically generated by json-schema-to-typescript.
 * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
 * and run json-schema-to-typescript to regenerate this file.
 */
var TargetProtocol;
(function (TargetProtocol) {
    TargetProtocol[TargetProtocol["SWD"] = 0] = "SWD";
    TargetProtocol[TargetProtocol["S3P"] = 1] = "S3P";
    TargetProtocol[TargetProtocol["JTAG"] = 2] = "JTAG";
    TargetProtocol[TargetProtocol["MODBUS"] = 3] = "MODBUS";
    TargetProtocol[TargetProtocol["DIRECT_IO"] = 4] = "DIRECT_IO";
    TargetProtocol[TargetProtocol["SERIAL"] = 6] = "SERIAL";
    TargetProtocol[TargetProtocol["CUSTOM"] = 7] = "CUSTOM";
    TargetProtocol[TargetProtocol["NONE"] = 255] = "NONE";
})(TargetProtocol || (TargetProtocol = {}));
/* tslint:disable */
/**
 * This file was automatically generated by json-schema-to-typescript.
 * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
 * and run json-schema-to-typescript to regenerate this file.
 */
var VariableFormat;
(function (VariableFormat) {
    VariableFormat[VariableFormat["_1_BIT"] = 0] = "_1_BIT";
    VariableFormat[VariableFormat["_8_BITS"] = 1] = "_8_BITS";
    VariableFormat[VariableFormat["_16_BITS"] = 2] = "_16_BITS";
    VariableFormat[VariableFormat["_32_BITS"] = 3] = "_32_BITS";
})(VariableFormat || (VariableFormat = {}));
/* tslint:disable */
/**
 * This file was automatically generated by json-schema-to-typescript.
 * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
 * and run json-schema-to-typescript to regenerate this file.
 */
var AppPathType;
(function (AppPathType) {
    AppPathType["PRIMER_CLOUD_WEB_APP_URL"] = "$1/";
    AppPathType["URL"] = "$2/";
    AppPathType["ANDROID_APP_ID"] = "$4/";
    AppPathType["PRIMER_CLOUD_CONFIG_URL"] = "$5/";
    AppPathType["AAR_2"] = "$6/";
})(AppPathType || (AppPathType = {}));
/* tslint:disable */
/**
 * This file was automatically generated by json-schema-to-typescript.
 * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file,
 * and run json-schema-to-typescript to regenerate this file.
 */
var SpecialFeature;
(function (SpecialFeature) {
    SpecialFeature[SpecialFeature["SWD_DIRECT_ACCESS"] = 100] = "SWD_DIRECT_ACCESS";
    SpecialFeature[SpecialFeature["SERIAL_ACCESS"] = 101] = "SERIAL_ACCESS";
    SpecialFeature[SpecialFeature["MODBUS_DIRECT_ACCESS"] = 102] = "MODBUS_DIRECT_ACCESS";
    SpecialFeature[SpecialFeature["TAPNPASS_CONTROL_ACCESS"] = 103] = "TAPNPASS_CONTROL_ACCESS";
    SpecialFeature[SpecialFeature["SP_CODEEXEC_ACCESS"] = 104] = "SP_CODEEXEC_ACCESS";
    SpecialFeature[SpecialFeature["MQTT_IDS_ACCESS"] = 105] = "MQTT_IDS_ACCESS";
})(SpecialFeature || (SpecialFeature = {}));

/**
 *   Generated file. Do not edit
 */
TapStreamReader.prototype.readTapVersion = function () {
    var model = {};
    model.major = this.readUnsigned(1);
    model.minor = this.readUnsigned(1);
    model.patch = this.readUnsigned(2);
    return model;
};
// TapStreamWriter.prototype.write(model: TapVersion) : TapStreamWriter{
//     return this.writeTapVersion(model)
// }
TapStreamWriter.prototype.writeTapVersion = function (model) {
    this.writeUnsigned(model.major !== undefined ? model.major : 0, 1);
    this.writeUnsigned(model.minor !== undefined ? model.minor : 0, 1);
    this.writeUnsigned(model.patch !== undefined ? model.patch : 0, 2);
    return this;
};

/**
 *   Generated file. Do not edit
 */
var TapVersionConverter = /** @class */ (function () {
    function TapVersionConverter() {
    }
    TapVersionConverter.prototype.encode = function (model, stream) {
        if (stream === void 0) { stream = new TapStreamWriter(); }
        stream.writeTapVersion(model);
        return stream.toBytes;
    };
    TapVersionConverter.prototype.decode = function (data) {
        var stream = data instanceof TapStreamReader ? data : TapStreamReader.create(data);
        return stream.readTapVersion();
    };
    return TapVersionConverter;
}());

/**
 * Generated bundle index. Do not edit.
 */

export { AbstractService, AppPathType, DEFAULT_TAP_MAX_FRAME_SIZE, HostProtocol, NFC_PAIRING_COMMAND, PathParameter, ServiceCallRunner, ServiceContainer, SpecialFeature, Tap, TapError, TapResponse, TapResponseStatusError, TapVersionConverter, TargetProtocol, VariableFormat, defaultValueIfTapRequetNotImplemented, defineTapPropertyExtension, extendServiceContainer, serviceCallToString, AppendChunkError as ɵa };
//# sourceMappingURL=iotize-tap.js.map
