(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@iotize/common/error'), require('@iotize/tap/service/impl/variable'), require('@iotize/common/byte-converter'), require('@iotize/common/byte-stream'), require('@iotize/common/data-accessor'), require('@iotize/tap'), require('@iotize/tap/configurator'), require('@iotize/tap/service/all'), require('@iotize/tap/service/core'), require('fast-xml-parser')) :
    typeof define === 'function' && define.amd ? define('@iotize/tap/config/iotize-studio', ['exports', '@iotize/common/error', '@iotize/tap/service/impl/variable', '@iotize/common/byte-converter', '@iotize/common/byte-stream', '@iotize/common/data-accessor', '@iotize/tap', '@iotize/tap/configurator', '@iotize/tap/service/all', '@iotize/tap/service/core', 'fast-xml-parser'], factory) :
    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory((global.iotize = global.iotize || {}, global.iotize.tap = global.iotize.tap || {}, global.iotize.tap.config = global.iotize.tap.config || {}, global.iotize.tap.config["iotize-studio"] = {}), global.error, global.iotize.tap.service.impl.variable, global.byteConverter, global.byteStream, global.dataAccessor, global.iotize.tap, global.iotize.tap.configurator, global.iotize.tap.service.all, global.iotize.tap.service.core, global.fastXmlParser));
})(this, (function (exports, error, variable, byteConverter, byteStream, dataAccessor, tap, configurator, all, core, fastXmlParser) { 'use strict';

    /*! *****************************************************************************
    Copyright (c) Microsoft Corporation.

    Permission to use, copy, modify, and/or distribute this software for any
    purpose with or without fee is hereby granted.

    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
    REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
    INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
    LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
    OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
    PERFORMANCE OF THIS SOFTWARE.
    ***************************************************************************** */
    /* global Reflect, Promise */
    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 (Object.prototype.hasOwnProperty.call(b, p))
                    d[p] = b[p]; };
        return extendStatics(d, b);
    };
    function __extends(d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    }
    var __assign = function () {
        __assign = Object.assign || function __assign(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);
    };
    function __rest(s, e) {
        var t = {};
        for (var p in s)
            if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
                t[p] = s[p];
        if (s != null && typeof Object.getOwnPropertySymbols === "function")
            for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
                if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                    t[p[i]] = s[p[i]];
            }
        return t;
    }
    function __decorate(decorators, target, key, desc) {
        var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
        if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
            r = Reflect.decorate(decorators, target, key, desc);
        else
            for (var i = decorators.length - 1; i >= 0; i--)
                if (d = decorators[i])
                    r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
        return c > 3 && r && Object.defineProperty(target, key, r), r;
    }
    function __param(paramIndex, decorator) {
        return function (target, key) { decorator(target, key, paramIndex); };
    }
    function __metadata(metadataKey, metadataValue) {
        if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
            return Reflect.metadata(metadataKey, metadataValue);
    }
    function __awaiter(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());
        });
    }
    function __generator(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 __createBinding = Object.create ? (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        Object.defineProperty(o, k2, { enumerable: true, get: function () { return m[k]; } });
    }) : (function (o, m, k, k2) {
        if (k2 === undefined)
            k2 = k;
        o[k2] = m[k];
    });
    function __exportStar(m, o) {
        for (var p in m)
            if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p))
                __createBinding(o, m, p);
    }
    function __values(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 __read(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;
    }
    /** @deprecated */
    function __spread() {
        for (var ar = [], i = 0; i < arguments.length; i++)
            ar = ar.concat(__read(arguments[i]));
        return ar;
    }
    /** @deprecated */
    function __spreadArrays() {
        for (var s = 0, i = 0, il = arguments.length; i < il; i++)
            s += arguments[i].length;
        for (var r = Array(s), k = 0, i = 0; i < il; i++)
            for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
                r[k] = a[j];
        return r;
    }
    function __spreadArray(to, from, pack) {
        if (pack || arguments.length === 2)
            for (var i = 0, l = from.length, ar; i < l; i++) {
                if (ar || !(i in from)) {
                    if (!ar)
                        ar = Array.prototype.slice.call(from, 0, i);
                    ar[i] = from[i];
                }
            }
        return to.concat(ar || Array.prototype.slice.call(from));
    }
    function __await(v) {
        return this instanceof __await ? (this.v = v, this) : new __await(v);
    }
    function __asyncGenerator(thisArg, _arguments, generator) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var g = generator.apply(thisArg, _arguments || []), i, q = [];
        return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
        function verb(n) { if (g[n])
            i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
        function resume(n, v) { try {
            step(g[n](v));
        }
        catch (e) {
            settle(q[0][3], e);
        } }
        function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
        function fulfill(value) { resume("next", value); }
        function reject(value) { resume("throw", value); }
        function settle(f, v) { if (f(v), q.shift(), q.length)
            resume(q[0][0], q[0][1]); }
    }
    function __asyncDelegator(o) {
        var i, p;
        return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
        function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
    }
    function __asyncValues(o) {
        if (!Symbol.asyncIterator)
            throw new TypeError("Symbol.asyncIterator is not defined.");
        var m = o[Symbol.asyncIterator], i;
        return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
        function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
        function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
    }
    function __makeTemplateObject(cooked, raw) {
        if (Object.defineProperty) {
            Object.defineProperty(cooked, "raw", { value: raw });
        }
        else {
            cooked.raw = raw;
        }
        return cooked;
    }
    ;
    var __setModuleDefault = Object.create ? (function (o, v) {
        Object.defineProperty(o, "default", { enumerable: true, value: v });
    }) : function (o, v) {
        o["default"] = v;
    };
    function __importStar(mod) {
        if (mod && mod.__esModule)
            return mod;
        var result = {};
        if (mod != null)
            for (var k in mod)
                if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k))
                    __createBinding(result, mod, k);
        __setModuleDefault(result, mod);
        return result;
    }
    function __importDefault(mod) {
        return (mod && mod.__esModule) ? mod : { default: mod };
    }
    function __classPrivateFieldGet(receiver, state, kind, f) {
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a getter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot read private member from an object whose class did not declare it");
        return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
    }
    function __classPrivateFieldSet(receiver, state, value, kind, f) {
        if (kind === "m")
            throw new TypeError("Private method is not writable");
        if (kind === "a" && !f)
            throw new TypeError("Private accessor was defined without a setter");
        if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
            throw new TypeError("Cannot write private member to an object whose class did not declare it");
        return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
    }

    var InvalidConfigurationError = /** @class */ (function (_super) {
        __extends(InvalidConfigurationError, _super);
        function InvalidConfigurationError(msg) {
            return _super.call(this, msg) || this;
        }
        return InvalidConfigurationError;
    }(error.BaseError));

    exports.ByteOrder32Bits = void 0;
    (function (ByteOrder32Bits) {
        ByteOrder32Bits[ByteOrder32Bits["B3_B2_B1_B0"] = 0] = "B3_B2_B1_B0";
        ByteOrder32Bits[ByteOrder32Bits["B1_B0_B3_B2"] = 1] = "B1_B0_B3_B2";
        ByteOrder32Bits[ByteOrder32Bits["B2_B3_B0_B1"] = 2] = "B2_B3_B0_B1";
        ByteOrder32Bits[ByteOrder32Bits["B0_B1_B2_B3"] = 3] = "B0_B1_B2_B3";
    })(exports.ByteOrder32Bits || (exports.ByteOrder32Bits = {}));
    exports.ByteOrder16Bits = void 0;
    (function (ByteOrder16Bits) {
        ByteOrder16Bits[ByteOrder16Bits["B1_B0"] = 0] = "B1_B0";
        ByteOrder16Bits[ByteOrder16Bits["B0_B1"] = 1] = "B0_B1";
    })(exports.ByteOrder16Bits || (exports.ByteOrder16Bits = {}));

    function toEnumFromValue(mapping, value) {
        var values = Object.keys(mapping).map(function (key) { return mapping[key]; });
        if (values.find(function (v) { return v.toString() === value; }) === undefined) {
            throw new Error("Missing value \"" + value + "\" in enum. Available keys are " + values.join(', '));
        }
        if (value in mapping) {
            // For string to number convertion
            return mapping[mapping[value]];
        }
        return value;
    }
    function toEnumType(value, mapping) {
        if (!(value in mapping)) {
            throw new Error("Missing mapping for " + value + ". Available: " + Object.keys(mapping).join(', '));
        }
        return mapping[value];
    }
    // export function toEnumFromKey<T>(mapping: any, key: string): T {
    //     if (!(key in mapping)) {
    //         throw new Error(`Missing key "${key}" in enum. Available keys are ${Object.keys(mapping).join(', ')}`);
    //     }
    //     return mapping[mapping[key]];
    // }

    var IotizeVariableModel = /** @class */ (function () {
        function IotizeVariableModel(data, iotizeModule, bundle) {
            this.data = data;
            this.iotizeModule = iotizeModule;
            if (bundle) {
                this._bundle = bundle;
            }
        }
        IotizeVariableModel.prototype.toJson = function () {
            return this.data;
        };
        IotizeVariableModel.prototype.module = function () {
            return this.iotizeModule;
        };
        /**
         * Size (int bits) of one element
         */
        IotizeVariableModel.prototype.valueSize = function () {
            return IotizeVariableModel.unitSizeToBitSize(parseInt(this.data.$.Unit));
        };
        IotizeVariableModel.prototype.valueQuantity = function () {
            return Number(this.data.$.Quantity);
        };
        IotizeVariableModel.prototype.name = function () {
            return this.data.$.GUI_Name;
        };
        IotizeVariableModel.prototype.id = function () {
            return this.data.$.Id;
        };
        IotizeVariableModel.prototype.alias = function () {
            return this.data.$.GUI_Alias;
        };
        IotizeVariableModel.prototype.description = function () {
            return this.data.$.GUI_Description;
        };
        IotizeVariableModel.prototype.unit = function () {
            return this.data.$.GUI_DispUnit;
        };
        IotizeVariableModel.prototype.bundle = function () {
            return this._bundle;
        };
        // public type(): VariableType.Data {
        //     if (this.data.$.GUI_float && this.data.$.GUI_float == 1) {
        //         return VariableType.Data.FLOAT32;
        //     } else if (this.data.$.GUI_unsigned && this.data.$.GUI_unsigned == 1) {
        //         return VariableType.Data.UINT32;
        //     } else {
        //         return VariableType.Data.INT32;
        //     }
        // }
        IotizeVariableModel.prototype.dataType = function () {
            var unit = parseInt(this.data.$.Unit, 10);
            if (this.data.$.GUI_float && this.data.$.GUI_float == 1) {
                return variable.VariableType.Data.FLOAT32;
            }
            else if (this.data.$.GUI_unsigned && this.data.$.GUI_unsigned == 1) {
                switch (unit) {
                    case 0:
                        return variable.VariableType.Data.BOOLEAN;
                    case 1:
                        return variable.VariableType.Data.UINT8;
                    case 2:
                        return variable.VariableType.Data.UINT16;
                    case 3:
                        return variable.VariableType.Data.UINT32;
                    default:
                        throw new Error("Invalid data size \"" + unit + "\" for variable " + this.name());
                }
            }
            else {
                switch (unit) {
                    case 0:
                        return variable.VariableType.Data.BOOLEAN;
                    case 1:
                        return variable.VariableType.Data.INT8;
                    case 2:
                        return variable.VariableType.Data.INT16;
                    case 3:
                        return variable.VariableType.Data.INT32;
                    default:
                        throw new Error("Invalid data size \"" + unit + "\" for variable " + this.name());
                }
            }
        };
        /**
         * Return attribute by name
         */
        IotizeVariableModel.prototype.attribute = function (name) {
            return this.data.$[name];
        };
        IotizeVariableModel.prototype.byteOrder = function () {
            var guiCoding = this.attribute('GUI_coding');
            if (guiCoding) {
                if (this.valueSize() === 16) {
                    return toEnumFromValue(exports.ByteOrder16Bits, guiCoding);
                }
                else if (this.valueSize() === 32) {
                    return toEnumFromValue(exports.ByteOrder32Bits, guiCoding);
                }
            }
            return undefined;
        };
        /**
         * Convert unit size found in configuration file into a number of bits
         */
        IotizeVariableModel.unitSizeToBitSize = function (unitSize) {
            switch (unitSize) {
                case 0:
                    return 1;
                case 1:
                    return 8;
                case 2:
                    return 16;
                case 3:
                    return 32;
                default:
                    throw new Error("Invalid unit size: " + unitSize);
            }
        };
        return IotizeVariableModel;
    }());

    var IotizeProfileModel = /** @class */ (function () {
        function IotizeProfileModel(data) {
            this.data = data;
        }
        IotizeProfileModel.prototype.toJson = function () {
            return this.data;
        };
        IotizeProfileModel.prototype.description = function () {
            return this.data.$.GUI_Description;
        };
        IotizeProfileModel.prototype.name = function () {
            return this.data.$.Name;
        };
        IotizeProfileModel.prototype.id = function () {
            return this.data.$.Id;
        };
        return IotizeProfileModel;
    }());

    var IotizeACL = /** @class */ (function () {
        function IotizeACL(data, aclGroup) {
            this.aclGroup = aclGroup;
            this.data = data;
        }
        IotizeACL.create = function (profileName, aclGroup) {
            return new IotizeACL({
                $: {
                    ProfileName: profileName,
                    Rights: '',
                },
            }, aclGroup);
        };
        IotizeACL.prototype.toJson = function () {
            return this.data;
        };
        IotizeACL.prototype.listRights = function () {
            var rights = this._getProperty('Rights', '');
            if (rights.length === 0) {
                return [];
            }
            return rights.split(',').map(function (entry) {
                return entry.trim();
            });
        };
        IotizeACL.prototype.username = function () {
            return this._getProperty('ProfileName');
        };
        IotizeACL.prototype.hasRight = function (name) {
            if (this.username() === 'admin') {
                return true;
            }
            var rights = this.listRights();
            return rights.indexOf(name) !== -1;
        };
        IotizeACL.prototype._getProperty = function (name, defaultValue) {
            if (!(name in this.data.$)) {
                if (defaultValue === undefined) {
                    throw new InvalidConfigurationError('Missing key ' + name + ' in IoTize ACL');
                }
                return defaultValue;
            }
            return this.data.$[name];
        };
        return IotizeACL;
    }());

    var ANONYMOUS_PROFILE = 'anonymous';
    /**
     *
     */
    var IotizeACLGroup = /** @class */ (function () {
        function IotizeACLGroup(data, bundle) {
            this.bundle = bundle;
            this.data = data;
        }
        IotizeACLGroup.prototype.toJson = function () {
            return this.data;
        };
        /**
         * Get acl for a profile
         * @param profileName
         */
        IotizeACLGroup.prototype.getByProfileName = function (profileName) {
            var e_1, _a;
            var profiles = this.listProfiles();
            try {
                for (var profiles_1 = __values(profiles), profiles_1_1 = profiles_1.next(); !profiles_1_1.done; profiles_1_1 = profiles_1.next()) {
                    var profileAcl = profiles_1_1.value;
                    if (profileAcl.username() === profileName) {
                        return profileAcl;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (profiles_1_1 && !profiles_1_1.done && (_a = profiles_1.return)) _a.call(profiles_1);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return IotizeACL.create(profileName, this);
        };
        IotizeACLGroup.prototype.hasRight = function (profileName, right) {
            var anonymousProfile = this.getByProfileName(ANONYMOUS_PROFILE);
            if (anonymousProfile && anonymousProfile.hasRight(right)) {
                return true;
            }
            if (profileName !== ANONYMOUS_PROFILE) {
                var profile = this.getByProfileName(profileName);
                if (profile) {
                    return profile.hasRight(right);
                }
            }
            return false;
        };
        /**
         * List acl entries for each profile
         */
        IotizeACLGroup.prototype.listProfiles = function () {
            var e_2, _a;
            if (!this.data.IOTizeACL) {
                return [];
            }
            var entries = [];
            try {
                for (var _b = __values(this.data.IOTizeACL), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var data = _c.value;
                    entries.push(new IotizeACL(data, this));
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_2) throw e_2.error; }
            }
            return entries;
        };
        return IotizeACLGroup;
    }());

    var IotizeBundleModel = /** @class */ (function () {
        function IotizeBundleModel(data, iotizeModule) {
            this.data = data;
            this.iotizeModule = iotizeModule;
        }
        IotizeBundleModel.prototype.toJson = function () {
            return this.data;
        };
        IotizeBundleModel.prototype.module = function () {
            return this.iotizeModule;
        };
        IotizeBundleModel.prototype.id = function () {
            if (!this.data.$.Id) {
                throw new InvalidConfigurationError('This bundle does not have an id');
            }
            return this.data.$.Id;
        };
        IotizeBundleModel.prototype.name = function () {
            return this.data.$.GUI_Name || '#' + this.id();
        };
        IotizeBundleModel.prototype.dataLogPeriod = function () {
            if (!this.data.$.DataLogPeriod) {
                return 0;
            }
            return Number(this.data.$.DataLogPeriod);
        };
        IotizeBundleModel.prototype.hasDataLog = function () {
            return this.dataLogPeriod() > 0;
        };
        IotizeBundleModel.prototype.description = function () {
            return this.data.$.GUI_Description;
        };
        IotizeBundleModel.prototype.variable = function (variableId) {
            var e_1, _a;
            try {
                for (var _b = __values(this.variables()), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var variable = _c.value;
                    if (variable.id() === variableId) {
                        return variable;
                    }
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            throw new VariableDoesNotExistError(variableId, this.iotizeModule);
        };
        IotizeBundleModel.prototype.hasVariable = function (variableId) {
            var e_2, _a;
            try {
                for (var _b = __values(this.variables()), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var variable = _c.value;
                    if (variable.id() === variableId) {
                        return variable;
                    }
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_2) throw e_2.error; }
            }
            return false;
        };
        IotizeBundleModel.prototype.profiles = function () {
            var e_3, _a;
            if (!this.data.IOTizeAccessControl) {
                return [];
            }
            var profiles = [];
            try {
                for (var _b = __values(this.data.IOTizeAccessControl), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var profile = _c.value;
                    profiles.push(new IotizeProfileModel(profile));
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_3) throw e_3.error; }
            }
            return profiles;
        };
        IotizeBundleModel.prototype.variables = function () {
            var e_4, _a;
            if (!this.data.IOTizeVariable) {
                return [];
            }
            var variables = [];
            try {
                for (var _b = __values(this.data.IOTizeVariable), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var variable = _c.value;
                    variables.push(new IotizeVariableModel(variable, this.iotizeModule, this));
                }
            }
            catch (e_4_1) { e_4 = { error: e_4_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_4) throw e_4.error; }
            }
            return variables;
        };
        IotizeBundleModel.prototype.getACLGroup = function () {
            var data = {};
            if (!this.data.IOTizeAccessControl) {
                this.data.IOTizeAccessControl = [];
            }
            if (this.data.IOTizeAccessControl.length > 0) {
                data = this.data.IOTizeAccessControl[0];
            }
            return new IotizeACLGroup(data, this);
        };
        return IotizeBundleModel;
    }());

    /**
     *
     */
    var BundleDoesNotExistError = /** @class */ (function (_super) {
        __extends(BundleDoesNotExistError, _super);
        // static CODE = 'BundleDoesNotExistError';
        function BundleDoesNotExistError(bundleId, config) {
            var _this = _super.call(this, 'Bundle "' + bundleId + '" does not exist.'
            // BundleDoesNotExistError.CODE
            ) || this;
            _this.bundleId = bundleId;
            _this.config = config;
            return _this;
        }
        return BundleDoesNotExistError;
    }(error.BaseError));
    /**
     *
     */
    var VariableDoesNotExistError = /** @class */ (function (_super) {
        __extends(VariableDoesNotExistError, _super);
        // static CODE = 'VariableDoesNotExistError';
        function VariableDoesNotExistError(variableId, config) {
            var _this = _super.call(this, "Variable \"" + variableId + "\" does not exist."
            // VariableDoesNotExistError.CODE
            ) || this;
            _this.variableId = variableId;
            _this.config = config;
            return _this;
        }
        return VariableDoesNotExistError;
    }(error.BaseError));
    /**
     * Class representing an iotize studio configuration for a module
     */
    var IotizeConfigModel = /** @class */ (function () {
        function IotizeConfigModel(data) {
            if (!data.IOTizeConfiguration) {
                //console.error('Trying to create an IotizeConfigModel with invalid data: ', data);
                throw new InvalidConfigurationError('Key IOTizeConfiguration must exists');
            }
            if (!data.IOTizeConfiguration.IOTizeApp) {
                throw new InvalidConfigurationError('Key IOTizeConfiguration.IOTizeApp must exists');
            }
            if (data.IOTizeConfiguration.IOTizeApp.length === 0 ||
                !data.IOTizeConfiguration.IOTizeApp[0]['$']) {
                throw new InvalidConfigurationError('No IOTizeConfiguration.IOTizeApp defined in this configuration file');
            }
            this.data = data;
        }
        IotizeConfigModel.prototype.toJson = function () {
            return this.data;
        };
        IotizeConfigModel.prototype.getAppConfig = function () {
            return this.data.IOTizeConfiguration.IOTizeApp[0];
        };
        /**
         * Get application name
         */
        IotizeConfigModel.prototype.appName = function () {
            if (!this.getAppConfig().$.Name) {
                throw new InvalidConfigurationError('Application Name is not set');
            }
            return this.getAppConfig().$.Name;
        };
        /**
         * Get config version
         */
        IotizeConfigModel.prototype.version = function () {
            if (!this.getAppConfig().$.Config) {
                throw new InvalidConfigurationError('App config version is not set');
            }
            return this.getAppConfig().$.Config;
        };
        /**
         * Get module serial number
         */
        IotizeConfigModel.prototype.id = function () {
            if (!this.getAppConfig().$.DevIoTizeSN) {
                throw new InvalidConfigurationError('Serial number is not set');
            }
            return this.getAppConfig().$.DevIoTizeSN;
        };
        /**
         * Set module serial number
         * @param id
         */
        IotizeConfigModel.prototype.setId = function (id) {
            this.getAppConfig().$.DevIoTizeSN = id;
            return this;
        };
        /**
         * Alias for this.id();
         */
        IotizeConfigModel.prototype.serialNumber = function () {
            return this.id();
        };
        /**
         * Get an array of all bundles
         */
        IotizeConfigModel.prototype.bundles = function () {
            var e_1, _a;
            if (!this.data.IOTizeConfiguration.IOTizeBundle) {
                return [];
            }
            var bundles = [];
            try {
                for (var _b = __values(this.data.IOTizeConfiguration.IOTizeBundle), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var bundle = _c.value;
                    // TODO bug if only one bundle
                    bundles.push(new IotizeBundleModel(bundle, this));
                }
            }
            catch (e_1_1) { e_1 = { error: e_1_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_1) throw e_1.error; }
            }
            return bundles;
        };
        /**
         * Array of bundles available for a specific profile
         */
        IotizeConfigModel.prototype.bundleAvailableForProfileName = function (profileName) {
            return this.bundles().reduce(function (list, currentValue) {
                if (currentValue.getACLGroup().hasRight(profileName, 'read')) {
                    list.push(currentValue);
                }
                return list;
            }, []);
        };
        /**
         * Get an array of all variables
         */
        IotizeConfigModel.prototype.variables = function () {
            var e_2, _a;
            if (!this.data.IOTizeConfiguration.IOTizeBundle) {
                return [];
            }
            var res = [];
            try {
                for (var _b = __values(this.data.IOTizeConfiguration.IOTizeBundle), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var bundle = _c.value;
                    bundle = new IotizeBundleModel(bundle, this);
                    res.push.apply(res, __spreadArray([], __read(bundle.variables())));
                }
            }
            catch (e_2_1) { e_2 = { error: e_2_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_2) throw e_2.error; }
            }
            return res;
        };
        /**
         * Get bundle by id, if it does not exist, throw BundleDoesNotExistError
         * @throws BundleDoesNotExistError
         * @param id
         */
        IotizeConfigModel.prototype.bundle = function (id) {
            var e_3, _a;
            try {
                for (var _b = __values(this.bundles()), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var bundle = _c.value;
                    if (bundle.id() === id) {
                        return bundle;
                    }
                }
            }
            catch (e_3_1) { e_3 = { error: e_3_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_3) throw e_3.error; }
            }
            throw new BundleDoesNotExistError(id, this);
        };
        IotizeConfigModel.prototype.hasBundle = function (id) {
            var e_4, _a;
            try {
                for (var _b = __values(this.bundles()), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var bundle = _c.value;
                    if (bundle.id() === id) {
                        return bundle;
                    }
                }
            }
            catch (e_4_1) { e_4 = { error: e_4_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_4) throw e_4.error; }
            }
            return false;
        };
        /**
         * Get variable by id, if it does not exist, throw VariableDoesNotExistError
         * @throws VariableDoesNotExistError
         * @param id
         */
        IotizeConfigModel.prototype.variable = function (variableId) {
            var e_5, _a;
            try {
                for (var _b = __values(this.variables()), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var variable = _c.value;
                    if (variable.id() == variableId) {
                        return variable;
                    }
                }
            }
            catch (e_5_1) { e_5 = { error: e_5_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_5) throw e_5.error; }
            }
            throw new VariableDoesNotExistError(variableId, this);
        };
        /**
         * Get an array of all profiles
         */
        IotizeConfigModel.prototype.profiles = function () {
            var e_6, _a;
            if (!this.data.IOTizeConfiguration.IOTizeProfile) {
                return [];
            }
            var profiles = [];
            try {
                for (var _b = __values(this.data.IOTizeConfiguration.IOTizeProfile), _c = _b.next(); !_c.done; _c = _b.next()) {
                    var profile = _c.value;
                    // TODO bug if there is only one profile...
                    profiles.push(new IotizeProfileModel(profile));
                }
            }
            catch (e_6_1) { e_6 = { error: e_6_1 }; }
            finally {
                try {
                    if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
                }
                finally { if (e_6) throw e_6.error; }
            }
            return profiles;
        };
        IotizeConfigModel.prototype.description = function () {
            return this.getAppConfig().$.GUI_Description;
        };
        IotizeConfigModel.prototype.name = function () {
            return this.getAppConfig().$.GUI_Name;
        };
        return IotizeConfigModel;
    }());

    /**
     * Utility class to create iotize config model from XML or JSON file
     */
    var IotizeConfigFactory = /** @class */ (function () {
        function IotizeConfigFactory() {
        }
        /**
         * Create IotizeConfigModel from a XML string
         * @param xml
         */
        IotizeConfigFactory.fromXML = function (xml) {
            throw new Error("Add import to @iotize/tap/config/iotize-studio/parser/xml to create configuration model from XML file");
        };
        /**
         * Create IotizeConfigModel from a JSON string
         * @param json
         */
        IotizeConfigFactory.fromJson = function (json) {
            return new IotizeConfigModel(JSON.parse(json));
        };
        /**
         * Build and IotizeConfigModel
         * Input can either be
         * - A json string
         * - A XML string
         * - A JSON Object
         *
         * TODO create test
         * @param data
         */
        IotizeConfigFactory.create = function (data) {
            if (typeof data === 'string') {
                data.trim();
                if (data.length === 0) {
                    throw new Error('Cannot create configuration from empty data');
                }
                if (data[0] === '{') {
                    return IotizeConfigFactory.fromJson(data);
                }
                else {
                    return IotizeConfigFactory.fromXML(data);
                }
            }
            else {
                return new IotizeConfigModel(data);
            }
        };
        return IotizeConfigFactory;
    }());

    var IoTizeStudioError = /** @class */ (function (_super) {
        __extends(IoTizeStudioError, _super);
        function IoTizeStudioError() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        IoTizeStudioError.invalidKeyValue = function (key, msg) {
            return new IoTizeStudioError("Invalid IoTize studio value for configuration key \"" + key + "\". " + msg, IoTizeStudioError.Code.InvalidConfigKeyValue);
        };
        return IoTizeStudioError;
    }(error.CodeError));
    (function (IoTizeStudioError) {
        var Code;
        (function (Code) {
            Code["InvalidConfigKeyValue"] = "IoTizeStudioErrorInvalidConfigKeyValue";
        })(Code = IoTizeStudioError.Code || (IoTizeStudioError.Code = {}));
    })(IoTizeStudioError || (IoTizeStudioError = {}));

    var NetworkModeMapping = {
        P2P: 'PEER_TO_PEER',
        NETWORK: 'NETWORK',
        INFRA: 'NETWORK',
        INFRA_CLOUD: 'NETWORK', // TODO check
    };
    var LowPowerOptimizationLevelMapping = {
        0: 'NO',
        1: 'SHUTDOWN',
        2: 'STANDBY', // TODO CHECK
    };
    var WIFI_KEY_VISIBILITY_MAPPING = {
        0: 'VISIBLE',
        1: 'HIDDEN',
    };
    var S3P_CONFIG_MODE_MAPPING = {
        0: 'EMULATION',
        1: 'INDEXED',
    };
    var WIFI_SSID_VISIBILITY_MAPPING = {
        0: 'VISIBLE',
        1: 'HIDDEN',
        2: 'HIDDEN_FROM_SCAN',
    };
    var WIFI_PROTOCOL_MAPPING = {
        1: ['B'],
        3: ['B', 'G'],
        7: ['B', 'G', 'N'],
    };
    var TargetProtocolMapping = {
        JTAG: 'JTAG',
        MODBUS: 'MODBUS',
        NONE: 'NONE',
        S3P: 'S3P',
        SERIAL: 'SERIAL',
        SERIAL_STANDARD: 'SERIAL',
        SERIAL_VIA_TAPNPASS: 'SERIAL',
        CUSTOM: 'CUSTOM',
        SWD: 'SWD',
        GPIO: 'DIRECT_IO',
        DIRECT_IO: 'DIRECT_IO',
        DIRECTIO: 'DIRECT_IO',
        CAN: 'CAN',
        NO_TARGET_PROTOCOL: 'NONE',
        MODBUSTCP: 'MODBUS_TCP',
    };
    var NFCParingModeMapping = {
        NO: 'NO',
        PAIRING: 'MANDATORY',
        'PAIRING+LOGIN': 'MANDATORY_FOR_LOGIN',
    };
    var NFC_CONNECTION_PRIORITY_MAPPING = {
        0: 'NFC_NON_PRIORITY',
        1: 'NFC_PRIORITY',
    };
    // const MAPPING: Record<WriteConfigKey, any> = {
    //     // App
    //     'application.name': 'IOTizeConfiguration.IOTizeApp.#.Name',
    //     'application.universalLink': 'IOTizeConfiguration.IOTizeApp.#.WebLink',
    //     'application.uri': 'IOTizeConfiguration.IOTizeApp.#.GUI_Path',
    //     'application.data': 'TODO',
    //     // CLOUD
    //     'cloud.dataLog.uploadPeriod': 'IOTizeConfiguration.IOTizeApp.CloudServices.#.CloudMqttPeriod',
    //     'cloud.dataLog.mqttPublishTopic': 'IOTizeConfiguration.IOTizeApp.WIFI_INFO.#.Cloud_Publish_Topic',
    //     'cloud.dataLog.mqttSubscribeTopic': 'IOTizeConfiguration.IOTizeApp.WIFI_INFO.#.Cloud_Subscribe_Topic',
    //     'cloud.platform': '',
    //     // Target
    //     'target.protocol.type': 'IOTizeConfiguration.IOTizeApp.#.TargetProtocol',
    //     // Tap
    //     'tap.certificate.privateKey': 'IOTizeConfiguration.IOTizeApp.GUI_MQTT_Info.GUI_DevMQTT_PrivateKey',
    //     'tap.certificate.publicKey': 'IOTizeConfiguration.IOTizeApp.GUI_MQTT_Info.GUI_DevMQTT_Certificate',
    //     // JVM
    //     'jvm.code': 'IOTizeConfiguration.IOTizeApp.#.JVM_Custom_Code',
    //     'jvm.profileId': 'IOTizeConfiguration.IOTizeApp.#.',
    //     // LORA
    //     'wireless.protocols.lora.config': 'IOTizeConfiguration.IOTizeApp.LoRa_Info.#.LoRaMode',
    //     'wireless.protocols.lora.ids': 'IOTizeConfiguration.IOTizeApp.LoRa_Info.#.TODO',
    //     // MQTT
    //     'wireless.protocols.mqtt.clientId': 'IOTizeConfiguration.IOTizeApp.WIFI_INFO.#.MQTTRelay_Client_ID',
    //     'wireless.protocols.mqtt.password': 'IOTizeConfiguration.IOTizeApp.WIFI_INFO.#.MQTTRelay_Passwd',
    //     'wireless.protocols.mqtt.username': 'IOTizeConfiguration.IOTizeApp.WIFI_INFO.#.MQTTRelay_Broker_Login',
    //     'wireless.protocols.mqtt.brokerPort': 'IOTizeConfiguration.IOTizeApp.WIFI_INFO.#.MQTTRelay_Service',
    //     'wireless.protocols.mqtt.brokerHostname': 'IOTizeConfiguration.IOTizeApp.WIFI_INFO.#.MQTTRelay_URL',
    //     'wireless.protocols.mqtt.brokerCertificate': 'IOTizeConfiguration.IOTizeApp.WIFI_INFO.#.Broker_Certificate',
    //     'wireless.protocols.mqtt.topicPrefix': 'IOTizeConfiguration.IOTizeApp.WIFI_INFO.#.TODO',
    //     // NFC
    //     'wireless.protocols.nfc.autoLogProfileId': 'IOTizeConfiguration.IOTizeApp.#.NFCLogin',
    //     'wireless.protocols.nfc.connectionPriority': 'IOTizeConfiguration.IOTizeApp.#.NFCInterruptionLock',
    //     'wireless.protocols.nfc.pairingMode': 'IOTizeConfiguration.IOTizeApp.#.NFCPairingMandatory',
    //     // WIFI
    //     'wireless.protocols.wifi.ssid': 'IOTizeConfiguration.IOTizeApp.WIFI_Info.ModuleSSID ||',
    //     'wireless.protocols.wifi.ssidVisibility': 'IOTizeConfiguration.IOTizeApp.WIFI_Info.Wifi_SSID_Hidden',
    //     'wireless.protocols.wifi.keyVisibility': 'IOTizeConfiguration.IOTizeApp.WIFI_Info.#.Wifi_WEPKey_Hidden',
    //     'wireless.protocols.wifi.gatewayIp': 'IOTizeConfiguration.IOTizeApp.WIFI_Info.#.',
    //     'wireless.protocols.wifi.mask': 'IOTizeConfiguration.IOTizeApp.WIFI_Info.#.',
    //     'wireless.protocols.wifi.mode': 'IOTizeConfiguration.IOTizeApp.WIFI_Info.#.',
    //     'wireless.protocols.wifi.protocol': 'IOTizeConfiguration.IOTizeApp.WIFI_Info.#.',
    //     'wireless.protocols.wifi.region': 'IOTizeConfiguration.IOTizeApp.WIFI_Info.#.',
    //     // Wireless options
    //     'wireless.options.inactivityTimeout': 'IOTizeConfiguration.IOTizeApp.WIFI_Info.#.',
    //     'wireless.options.authorizedProtocols': 'IOTizeConfiguration.IOTizeApp.WIFI_Info.#.',
    //     'data.profiles[]': 'IOTizeConfiguration.IOTizeApp.IOTizeProfile',
    //     'data.profiles[].username': '#.Name',
    //     'data.profiles[].alias': '#.GroupId',
    //     'data.profiles[].lifeTime': '#.LifeTime',
    //     'data.profiles[].passwordKey': '#.Pwd',
    //     'data.profiles[].password': false,
    //     'data.bundles[]': 'IOTizeConfiguration.IOTizeApp.IOTizeBundle',
    //     'data.bundles[].name': '#.Name',
    //     'data.bundles[].dataLog.period': '#.DataLogPeriod',
    //     'data.bundles[].acl[].$': '#.',
    //     'data.variables[].address': '',
    //     'data.variables[].bundleId': '',
    //     'data.variables[].type': '',
    //     'data.variables[].value': '',
    // }

    function isTruthy(v, falsyValue) {
        if (falsyValue === void 0) { falsyValue = ['no', 'false', '0']; }
        if (v === undefined) {
            return false;
        }
        if (falsyValue.indexOf(v.toString().toLowerCase()) >= 0) {
            return false;
        }
        return !!v;
    }
    function convertToVariableType(accessor) {
        var unsigned = isTruthy(accessor.value('GUI_unsigned', 'string', '0'));
        var float = isTruthy(accessor.value('GUI_float', 'string', '0'));
        var unitSize = accessor.value('Unit', 'number', 1);
        if (unitSize === 1) {
            var xAppRender = accessor.get('XAppRender', undefined);
            if (xAppRender) {
                var xAppRenderUnitType = xAppRender.value('GUI_UnitType', 'string', undefined);
                if (xAppRenderUnitType === 'ASCII') {
                    return variable.VariableType.Data.ASCII;
                }
            }
        }
        // Old version of IoTize Studio was storing UnitType ?
        var unitDataType = accessor.value('UnitType', 'string', '');
        if (unitDataType) {
            if (unitDataType === 'boolean') {
                return variable.VariableType.Data.BOOLEAN;
            }
            else if (unitDataType === 'ASCII') {
                return variable.VariableType.Data.ASCII;
            }
            else {
                unsigned = unitDataType === 'unsigned integer';
                float = unitDataType === 'float';
            }
        }
        if (float) {
            return variable.VariableType.Data.FLOAT32;
        }
        switch (unitSize) {
            case 0:
                return unsigned ? variable.VariableType.Data.UINT8 : variable.VariableType.Data.INT8;
            case 1:
                return unsigned ? variable.VariableType.Data.UINT8 : variable.VariableType.Data.INT8;
            case 2:
                return unsigned ? variable.VariableType.Data.UINT16 : variable.VariableType.Data.INT16;
            case 3:
                return unsigned ? variable.VariableType.Data.UINT32 : variable.VariableType.Data.INT32;
            default:
                throw new Error("Unknown unit size: \"" + unitSize + "\" (type=" + typeof unitSize + ")");
        }
    }
    function fromMapping(data, attributeName, mapping, defaultValue) {
        var value = data.value(attributeName, 'string', defaultValue);
        if (!value) {
            return undefined;
        }
        value = value.replace(/ /g, '_').toUpperCase();
        if (!(value in mapping)) {
            throw new Error("Invalid value \"" + value + "\" for key \"" + attributeName + "\"");
        }
        return mapping[value];
    }
    /**
     * TODO add to common lib (toEnumFromValue)
     * @param mapping
     * @param value
     */
    function stringToEnum(mapping, value) {
        var values = Object.keys(mapping).map(function (key) { return mapping[key]; });
        if (values.find(function (v) { return v.toString() === value; }) === undefined) {
            throw new Error("Missing value \"" + value + "\" in enum. Available keys are " + values.join(', '));
        }
        if (value in mapping) {
            // For string to number convertion
            return mapping[mapping[value]];
        }
        return value;
    }
    function mapKey(object, key, value) {
        if (value) {
            object[key] = value;
        }
    }
    // /**
    //  * Checks if current bundle can be seen by the current user
    //  * @param {string} profile name of the profile
    //  * @returns {boolean} true if bundle is visible to the user
    //  */
    // isVisibleTo(profile: string) {
    //         let isVisible;
    //         switch (profile) {
    //                 case 'admin':
    //                 return true;
    //                 case 'supervisor':
    //                 return (this.rights.length !== 1 || this.rights.find( right => right.profile === 'admin') === undefined);
    //                 default :
    //                 isVisible = this.rights.find( right => right.profile === profile? true : right.profile === 'anonymous');
    //         }
    //         return isVisible !== undefined ? true : false;
    // }
    // /**
    //  * Checks if current bundle can be written by the current user
    //  * @param profile name of the profile
    //  * @returns {boolean} true if bundle is writable by the user
    //  */
    // isWritableBy(profile: string) {
    //         switch (profile) {
    //                 case 'admin':
    //                 return this.rights.find(right => right.write) !== undefined;
    //                 case 'supervisor':
    //                 return this.rights.find(right => (right.write && right.profile !== 'admin')) !== undefined;
    //                 default :
    //                 const profileRights = this.rights.find( right => right.profile === profile);
    //                 const anonymousRights = this.rights.find( right => right.profile === 'anonymous');
    //                 return (profileRights && profileRights.write)? true : (anonymousRights && anonymousRights.write)? true : false;
    //         }
    // }

    function xmlToJson(xml) {
        return fastXmlParser.parse(xml, {
            attributeNamePrefix: '',
            ignoreAttributes: false,
        });
    }
    function convertIoTizeStudioConfigToTapConfig(fileContent) {
        // console.log('File content', fileContent);
        var config = new IoTizeStudioToTapConfigConverter().convert(new dataAccessor.DotAccessor(xmlToJson(fileContent)));
        return config;
    }
    function isHexString(input) {
        if (typeof input !== 'string') {
            return false;
        }
        return input.match(/^(0x)?([a-fA-F0-9])*$/);
    }
    function decodeInitialVariableValue(value) {
        var values = value
            .split(';')
            .reduce(function (prev, v) {
            if (v.length === 0) {
                return prev;
            }
            if (v.startsWith('0x')) {
                prev.push(v);
            }
            else {
                prev.push(parseFloat(v));
            }
            return prev;
        }, []);
        return values.length > 0
            ? values.length === 1
                ? values[0]
                : values
            : undefined;
    }
    function addNodeValueIfExist(data, config, mapping, method) {
        if (method === void 0) { method = 'string'; }
        Object.entries(mapping).forEach(function (_c) {
            var _d = __read(_c, 2), iotzName = _d[0], apiName = _d[1];
            var _a;
            var value = (_a = data
                .get(iotzName, undefined)) === null || _a === void 0 ? void 0 : _a.value('Name', method, undefined);
            if (value) {
                config[apiName] = value;
            }
        });
    }
    function addAttributeIfExist(data, config, iotzName, apiName, method) {
        var value = data === null || data === void 0 ? void 0 : data.value(iotzName, method, undefined);
        if (value !== undefined && value !== '') {
            config[apiName] = value;
        }
    }
    function addAttributesIfExists(data, config, mapping, method) {
        if (method === void 0) { method = 'string'; }
        Object.entries(mapping).forEach(function (_c) {
            var _d = __read(_c, 2), iotzName = _d[0], apiName = _d[1];
            addAttributeIfExist(data, config, iotzName, apiName, method);
        });
    }
    /**
     * Convert an IoTize studio configuration file to TapConfiguratorConfig
     */
    var IoTizeStudioToTapConfigConverter = /** @class */ (function () {
        function IoTizeStudioToTapConfigConverter(options, host) {
            if (options === void 0) { options = {
                strict: false,
            }; }
            this.options = options;
            this.host = host;
            /**
             * Errors reported during convertion when strict mode is disabled
             */
            this.warnings = [];
            this.modbusSerialConfigConverter = new all.TapnpassProtocolConfigurationConverter();
        }
        IoTizeStudioToTapConfigConverter.prototype.convert = function (root) {
            var config = root.get('IOTizeConfiguration');
            var appConfigNode = config.get('IOTizeApp');
            var wifiConfigNode = appConfigNode.get('WIFI_Info', undefined);
            var bundles = config.list('IOTizeBundle', []);
            var profiles = config.list('IOTizeProfile', []);
            var versionString = config.value('Version', 'string', '1.0.0');
            var result = {
                version: versionString,
                application: this.readApplicationConfig(appConfigNode),
                data: {
                    bundles: this.readBundlesConfig(bundles),
                    profiles: this.readProfilesConfig(profiles),
                },
                cloud: this.readCloudConfig(appConfigNode),
                jvm: this.readJvmConfig(config),
                wireless: {
                    options: this.readWirelessOptionsConfig(appConfigNode),
                    protocols: {
                        wifi: this.readWifiConfig(wifiConfigNode),
                        mqtt: this.readMqttConfig(wifiConfigNode),
                        ble: this.readBleConfig(appConfigNode),
                        lora: this.readLoraConfig(appConfigNode),
                        nfc: this.readNfcConfig(appConfigNode),
                    },
                },
                tap: this.readTapConfig(appConfigNode),
                target: this.readTargetConfig(appConfigNode),
            };
            var slaveServerConfig = this.readSlaveServerConfig(appConfigNode);
            if (slaveServerConfig) {
                result.slaveServer = slaveServerConfig;
            }
            var ethernet = this.readEthernetConfig(appConfigNode);
            if (ethernet) {
                result.ports = {
                    ethernet: ethernet,
                };
            }
            if (this.warnings.length > 0) {
                // TODO
            }
            return result;
        };
        IoTizeStudioToTapConfigConverter.prototype.reportError = function (error, message) {
            if (message === void 0) { message = error.message; }
            if (this.options.strict) {
                throw error;
            }
            this.warnings.push({
                error: error,
                message: message,
            });
        };
        IoTizeStudioToTapConfigConverter.prototype.readSlaveServerConfig = function (appConfig) {
            if (!appConfig) {
                return undefined;
            }
            var channel = appConfig.value('MBS_Com_Channel', 'number', 0);
            switch (channel) {
                case all.SlaveServerRawConfig.Channel.CAN:
                    return {
                        type: 'CAN',
                        config: this.readCanProtocolConfig(appConfig),
                    };
                case all.SlaveServerRawConfig.Channel.MODBUS_RTU:
                    var targetProtocolConfDataLen = appConfig.value('MBSProtocolConfDataLen', 'number', 0);
                    var protocolData = byteConverter.hexStringToBuffer(appConfig.value('MBSProtocolConfData', 'string', ''));
                    return {
                        type: 'MODBUS_RTU',
                        config: this._protocolDataToJsonConfig(protocolData, targetProtocolConfDataLen),
                    };
                case all.SlaveServerRawConfig.Channel.MODBUS_TCP:
                    return {
                        type: 'MODBUS_TCP',
                        config: {
                            port: appConfig.value('MBS_ModbusTCP_Port', 'number', 502),
                            firstRegisterAddress: appConfig.value('MBS_ModbusTCP_Addr0', 'number', 0),
                        },
                    };
                case all.SlaveServerRawConfig.Channel.SPI:
                    return {
                        type: 'SPI',
                    };
                case all.SlaveServerRawConfig.Channel.DISABLED:
                    return undefined;
                default:
                    throw new Error('Invalid config'); // TODO proper error
            }
        };
        IoTizeStudioToTapConfigConverter.prototype.readMqttConfig = function (cloudServicesConfig) {
            var _a;
            if (!cloudServicesConfig) {
                return undefined;
            }
            var config = {};
            addNodeValueIfExist(cloudServicesConfig, config, {
                CloudHostName: 'brokerHostname',
                CloudServiceName: 'brokerPort',
                CloudMQTT_UID: 'password',
                GUI_DevNetkey: 'netKey',
                GUI_DevMQTT_ClientID: 'clientId',
                CloudMQTT_USERNAME: 'username',
            });
            var brokerCertificate = this.readFileContentAsHexString((_a = cloudServicesConfig
                .get('AWSRootCertificate', undefined)) === null || _a === void 0 ? void 0 : _a.value('Name', 'string', undefined));
            if (brokerCertificate) {
                config.brokerCertificate = brokerCertificate;
            }
            return config;
        };
        IoTizeStudioToTapConfigConverter.prototype.readLoraConfig = function (appConfigNode) {
            return {
                config: undefined,
                ids: undefined,
            };
        };
        IoTizeStudioToTapConfigConverter.prototype.readBleConfig = function (appConfigNode) {
            return {};
        };
        IoTizeStudioToTapConfigConverter.prototype.readNfcConfig = function (appConfigNode) {
            return {
                autoLogProfileId: appConfigNode.value('NFCLogin', 'number', undefined),
                connectionPriority: fromMapping(appConfigNode, 'NFCInterruptionLock', NFC_CONNECTION_PRIORITY_MAPPING, undefined),
            };
        };
        IoTizeStudioToTapConfigConverter.prototype.readWifiConfig = function (wifiConfigNode) {
            if (!wifiConfigNode) {
                return undefined;
            }
            var mode = fromMapping(wifiConfigNode, 'Network', NetworkModeMapping, 'P2P');
            var isAP = mode === 'PEER_TO_PEER';
            var config = {
                mode: mode,
            };
            addAttributeIfExist(wifiConfigNode, config, 'ModuleIPMask', 'mask', 'string');
            addAttributeIfExist(wifiConfigNode, config, 'ModuleIPGateway', 'gatewayIp', 'string');
            addAttributeIfExist(wifiConfigNode, config, 'ModuleIPAddress', 'ip', 'string');
            addAttributeIfExist(wifiConfigNode, config, 'Wifi_TxLevel', 'txPower', 'number');
            var keyVisibility = fromMapping(wifiConfigNode, 'Wifi_WEPKey_Hidden', WIFI_KEY_VISIBILITY_MAPPING, undefined);
            if (keyVisibility !== undefined) {
                config.keyVisibility = keyVisibility;
            }
            var protocol = fromMapping(wifiConfigNode, 'Wifi_Protocol', WIFI_PROTOCOL_MAPPING, undefined);
            if (protocol) {
                config.protocol = protocol;
            }
            addAttributeIfExist(wifiConfigNode, config, 'Wifi_Region', 'countryCode', 'number');
            var ssidVisibility = fromMapping(wifiConfigNode, 'Wifi_SSID_Hidden', WIFI_SSID_VISIBILITY_MAPPING, undefined);
            if (ssidVisibility) {
                config.ssidVisibility = ssidVisibility;
            }
            addAttributeIfExist(wifiConfigNode, config, isAP ? 'Module_AP_SSID' : 'ModuleSSID', 'ssid', 'string');
            addAttributeIfExist(wifiConfigNode, config, isAP ? 'Module_AP_WEPKey' : 'ModuleWEPKey', 'key', 'string');
            return config;
        };
        IoTizeStudioToTapConfigConverter.prototype.toAuthorizedHostProtocols = function (value) {
            var _this = this;
            if (!value || value === 'ALL' || value === 'FFFF') {
                return undefined;
            }
            if (isHexString(value)) {
                var encodedValue = byteConverter.hexStringToBuffer(value);
                return core.converters.hostProtocolArray.decode(encodedValue).map(function (p) {
                    return tap.HostProtocol[p];
                });
            }
            else {
                return value.split(',').reduce(function (prev, value) {
                    value = value.trim();
                    try {
                        // TODO check it's a read HostProtocolConfig...
                        prev.push(value); //stringToEnum<HostProtocolConfig>(HostProtocolConfig, value));
                    }
                    catch (err) {
                        _this.reportError(err);
                    }
                    return prev;
                }, []);
            }
        };
        IoTizeStudioToTapConfigConverter.prototype.readAuthorizedHostProtocols = function (appConfigNode) {
            var availableHostProtocols = undefined;
            var hostProtocolString = appConfigNode.value('HostProtocol', 'string', undefined);
            try {
                availableHostProtocols =
                    this.toAuthorizedHostProtocols(hostProtocolString);
            }
            catch (err) {
                this.reportError(err, "Cannot convert HostProtocol value \"" + hostProtocolString + "\"");
            }
            return availableHostProtocols && availableHostProtocols.length > 0
                ? availableHostProtocols
                : undefined;
        };
        IoTizeStudioToTapConfigConverter.prototype.readWirelessOptionsConfig = function (appConfigNode) {
            var wirelessOptionsConfig = {
                inactivityTimeout: appConfigNode.value('LowPowerHostTimeout', 'number', 0),
            };
            var authorizedProtocols = this.readAuthorizedHostProtocols(appConfigNode);
            if (authorizedProtocols) {
                wirelessOptionsConfig.authorizedProtocols = authorizedProtocols;
            }
            var nfcPairingMode = fromMapping(appConfigNode, 'NFCPairingMandatory', NFCParingModeMapping, undefined);
            var blePairing = appConfigNode.value('BLEPairingRequest', 'boolean', undefined);
            if (nfcPairingMode !== undefined || blePairing !== undefined) {
                wirelessOptionsConfig.pairing = {
                    blePairing: blePairing,
                    nfcPairingMode: nfcPairingMode,
                };
            }
            return wirelessOptionsConfig;
        };
        IoTizeStudioToTapConfigConverter.prototype.readJvmConfig = function (config) {
            var appConfigNode = config.get('IOTizeApp');
            var envNode = config.get('GUI_Environment', undefined);
            var bcbFile = appConfigNode.value('JVM_Custom_Code', 'string', undefined);
            var useJvm = envNode === null || envNode === void 0 ? void 0 : envNode.value('UseInternalJVM', 'boolean', false);
            if (!useJvm) {
                return undefined;
            }
            return {
                code: bcbFile ? this.readFileContentAsHexString(bcbFile) : undefined,
                // profileId: appConfigNode.value('TODO', 'number', undefined) // TODO
            };
        };
        IoTizeStudioToTapConfigConverter.prototype.readEthernetConfig = function (accessor) {
            var data = {};
            addAttributesIfExists(accessor, data, {
                EthernetIPAddress: 'ip',
                EthernetIPGateway: 'gatewayIp',
                EthernetIPMask: 'ipMask',
            });
            if (Object.keys(data).length === 0) {
                return undefined;
            }
            return data;
        };
        IoTizeStudioToTapConfigConverter.prototype.readFileContentAsHexString = function (path) {
            if (!path) {
                return undefined;
            }
            if (!this.host) {
                this.reportError(new Error("External file reference \"" + path + "\" cannot be resolved"));
            }
            if (this.host) {
                try {
                    var fileContent = this.host.getFileContent(path);
                    return '0x' + byteConverter.bufferToHexString(fileContent);
                }
                catch (err) {
                    this.reportError(err);
                }
            }
            return undefined;
        };
        IoTizeStudioToTapConfigConverter.prototype.readCloudConfig = function (appConfigNode) {
            var cloudService = appConfigNode.get('CloudServices', undefined);
            // TODO cloud services
            // if (cloudService?.has('CloudMQTT_UID')) {
            //     let url = '';
            //     const cloudHostName = cloudService.get('CloudHostName', undefined);
            //     const cloudServiceName = cloudService.get('CloudServiceName', undefined);
            //     if (cloudHostName) {
            //         url = `mqtt://${cloudHostName.value('Name', 'string', '')}:${cloudServiceName?.value('Name', 'string', '') || ''}`;
            //     }
            //     // cloud = {
            //     //     // password: cloudService
            //     //     //     .get('CloudMQTT_UID', undefined)
            //     //     //     ?.value('Name', 'string', '') || '',
            //     //     uploadPeriod: ,
            //     //     url
            //     // };
            // }
            var wifiNode = appConfigNode.get('WIFI_Info', undefined);
            var cloudConfig = {};
            var dataLogConfig = {};
            if (wifiNode) {
                addAttributesIfExists(wifiNode, dataLogConfig, {
                    Cloud_Publish_Topic: 'mqttPublishTopic',
                    Cloud_Subscribe_Topic: 'mqttSubscribeTopic',
                });
            }
            if (cloudService) {
                addAttributesIfExists(cloudService, dataLogConfig, {
                    CloudMqttPeriod: 'uploadPeriod',
                }, 'number');
            }
            if (Object.keys(dataLogConfig).length > 0) {
                cloudConfig.dataLog = dataLogConfig;
            }
            if (Object.keys(cloudConfig).length > 0) {
                return cloudConfig;
            }
            else {
                return undefined;
            }
        };
        IoTizeStudioToTapConfigConverter.prototype.readApplicationConfig = function (appConfigNode) {
            var appPath = appConfigNode.has('GUI_Path')
                ? appConfigNode.value('GUI_Path', 'string', '')
                : appConfigNode.value('Path', 'string', '');
            // const appPathInfo = this.appPathConverter.decode(appPath);
            var config = {
                name: appConfigNode.value('Name', 'string', 'Tap'),
                universalLink: appConfigNode.value('WebLink', 'string', ''),
                uri: appPath,
            };
            var productCode = appConfigNode.value('ProductCode', 'string', undefined);
            if (productCode !== undefined) {
                config.productCode = productCode;
            }
            var additionalData = appConfigNode.value('Data', 'string', undefined);
            if (additionalData !== undefined) {
                config.data = "0x" + byteConverter.bufferToHexString(byteConverter.asciiStringToByteBuffer(additionalData));
            }
            return config;
        };
        IoTizeStudioToTapConfigConverter.prototype.readTapConfig = function (appConfigNode) {
            var _a, _b;
            var lockSettingsEncoded = appConfigNode.value('InterfaceLock', 'number', 0);
            var lockOptions = new all.SecurityOptionsConverter().decode(Uint8Array.from([0, lockSettingsEncoded])); // TODO pad instead
            var tapOptions = {
                security: lockOptions,
                powerOptimization: fromMapping(appConfigNode, 'LowPowerLevel', LowPowerOptimizationLevelMapping, undefined),
                scram: {
                    hashIteration: appConfigNode.value('Scram_Hash_It', 'number', 5000),
                },
                certificate: {
                    publicKey: this.readFileContentAsHexString((_a = appConfigNode
                        .get('DeviceCertificate', undefined)) === null || _a === void 0 ? void 0 : _a.value('Name', 'string', undefined)),
                    privateKey: this.readFileContentAsHexString((_b = appConfigNode
                        .get('DevicePrivateKey', undefined)) === null || _b === void 0 ? void 0 : _b.value('Name', 'string', undefined)),
                },
            };
            var timeZoneStr = appConfigNode.value('TimeZoneStr', 'string', undefined);
            var ntpServer = appConfigNode.value('NTP_URL', 'string', undefined);
            if (timeZoneStr || ntpServer) {
                tapOptions.time = {
                    zone: timeZoneStr,
                    ntpServer: ntpServer,
                };
            }
            return tapOptions;
        };
        IoTizeStudioToTapConfigConverter.prototype.readTapTimeConfig = function (appConfigNode) {
            var zone = appConfigNode.value('TimeZoneStr', 'string', undefined);
            var ntpServer = appConfigNode.value('NTP_URL', 'string', undefined);
            if (zone || ntpServer) {
                return {
                    zone: zone,
                    ntpServer: ntpServer,
                };
            }
            return undefined;
        };
        IoTizeStudioToTapConfigConverter.prototype.readTargetConfig = function (appConfig) {
            var firmwareVersion = appConfig.value('Firmware', 'string', undefined);
            if (appConfig.value('GUI_TargetType', 'string', '0') === '1') {
                return {
                    type: 'TAPNPASS',
                    protocol: {
                        config: this.readTapnpassTargetProtocolConfig(appConfig),
                    },
                    firmwareVersion: firmwareVersion,
                };
            }
            else {
                var protocol = this.readMCUTargetProtocol(appConfig);
                if (!protocol) {
                    return undefined;
                }
                return {
                    type: 'MCU',
                    protocol: protocol,
                    firmwareVersion: firmwareVersion,
                };
            }
            // if (appConfig.has('USB_Aliases')) {
            //   data.type = "TAPNPASS";
            //   (data as TapNPassTargetConfig).usb = this._convertUsbData(appConfig);
            // }
        };
        IoTizeStudioToTapConfigConverter.prototype.readTargetProtocol = function (appConfig) {
            // const targetProtocolString = appConfig.value('TargetProtocol', 'string', 'SWD');
            return fromMapping(appConfig, 'TargetProtocol', TargetProtocolMapping, 'NONE');
        };
        IoTizeStudioToTapConfigConverter.prototype.readTapnpassTargetProtocol = function (appConfig) {
            var targetProtocol = this.readTargetProtocol(appConfig);
            switch (targetProtocol) {
                case 'SERIAL':
                    var serialConfig = {
                        type: 'SERIAL',
                        config: this.readTapnpassTargetProtocolConfig(appConfig),
                    };
                    return serialConfig;
                case 'MODBUS':
                    var modbusConfig = {
                        type: 'MODBUS',
                        config: this.readTapnpassTargetProtocolConfig(appConfig),
                    };
                    return modbusConfig;
                default:
                    throw new Error("Illegal target protocol \"" + (targetProtocol === null || targetProtocol === void 0 ? void 0 : targetProtocol.toString()) + "\" for TapNPass target type.");
            }
        };
        IoTizeStudioToTapConfigConverter.prototype.readTapnpassTargetProtocolConfig = function (appConfig) {
            var targetProtocolConfDataLen = appConfig.value('TargetProtocolConfDataLen', 'number', 0);
            var protocolData = byteConverter.hexStringToBuffer(appConfig.value('TargetProtocolConfData', 'string', ''));
            return this._protocolDataToJsonConfig(protocolData, targetProtocolConfDataLen);
        };
        IoTizeStudioToTapConfigConverter.prototype.readMCUTargetProtocol = function (appConfig) {
            var targetProtocol = this.readTargetProtocol(appConfig);
            switch (targetProtocol) {
                case 'SWD':
                    return {
                        type: targetProtocol,
                    };
                case 'CUSTOM':
                    return {
                        type: 'CUSTOM',
                        // config: '0xTODO'
                    };
                case 'MODBUS':
                    return {
                        type: 'MODBUS',
                        config: this.readModbusProtocolConfig(appConfig),
                    };
                case 'S3P':
                    return {
                        type: 'S3P',
                        config: this.readS3PProtocolConfig(appConfig),
                    };
                case 'SERIAL':
                    var serialConfig = {
                        type: 'SERIAL',
                        config: this.readTapnpassTargetProtocolConfig(appConfig),
                    };
                    return serialConfig;
                case 'NONE':
                    return undefined;
                case 'DIRECT_IO':
                    return {
                        type: 'DIRECT_IO',
                    };
                case 'CAN':
                    return {
                        type: 'CAN',
                        config: this.readCanProtocolConfig(appConfig),
                    };
                case 'MODBUS_TCP':
                    return {
                        type: 'MODBUS_TCP',
                        config: this.readModbusTcpProtocolConfig(appConfig),
                    };
                case 'JTAG':
                default:
                    throw new Error("Target protocol convertion from \"" + (targetProtocol === null || targetProtocol === void 0 ? void 0 : targetProtocol.toString()) + "\" is not supported yet.");
            }
        };
        IoTizeStudioToTapConfigConverter.prototype.readSerialProtocolConfig = function (appConfig) {
            var config = this.readModbusProtocolConfig(appConfig);
            if (!config) {
                return undefined;
            }
            return config === null || config === void 0 ? void 0 : config.serial;
        };
        IoTizeStudioToTapConfigConverter.prototype.readS3PProtocolConfig = function (appConfig) {
            return {
                mode: fromMapping(appConfig, 'S3Pmode', S3P_CONFIG_MODE_MAPPING) || 'EMULATION',
                delay: appConfig.value('S3PDelay', 'number', 1),
            };
        };
        /**
         * CAN_Freqkbps="0" CAN_Mode="1" CAN_Filter="1" CAN_Code="305419896" CAN_Mask="2596069104"
         * @param appConfig
         * @returns
         */
        IoTizeStudioToTapConfigConverter.prototype.readCanProtocolConfig = function (appConfig) {
            return {
                frequency: appConfig.value('CAN_Freqkbps', 'number', 25),
                mode: fromMapping(appConfig, 'CAN_Mode', all.TargetCanProtocolConfiguration.Mode) || 'NORMAL',
                filter: fromMapping(appConfig, 'CAN_Filter', all.TargetCanProtocolConfiguration.Filter) || 'SINGLE',
                code: toHexNumberConfig(appConfig.value('CAN_Code', 'number', 0x0)),
                mask: toHexNumberConfig(appConfig.value('CAN_Mask', 'number', 0xffffffff)),
            };
        };
        IoTizeStudioToTapConfigConverter.prototype.readModbusTcpProtocolConfig = function (node) {
            var data = {
                modbus: {},
            };
            addAttributesIfExists(node, data['modbus'], {
                ModbusTCPDefSlaveAddr: 'defaultSlaveAddress',
            });
            addAttributesIfExists(node, data['modbus'], {
                ModbusTCPAddr0: 'firstRegisterAddress',
                ModbusTCPPort: 'port',
                ModbusTCPTimeout: 'timeout',
            }, 'number');
            if (Object.keys(data).length === 0) {
                return undefined;
            }
            return data;
        };
        IoTizeStudioToTapConfigConverter.prototype.readModbusProtocolConfig = function (appConfig) {
            var config = this.readTapnpassTargetProtocolConfig(appConfig);
            var partialSerial = config.serial;
            delete partialSerial.identification;
            delete partialSerial.physicalPort;
            delete partialSerial.hardwareFlowControl;
            delete partialSerial.ledStatus;
            return {
                modbus: config.modbus,
                serial: config.serial,
            };
        };
        IoTizeStudioToTapConfigConverter.prototype.toEnumKey = function (value, mapping
        // , defaultValue: (keyof MappingType)
        ) {
            // if (value === undefined) {
            //     return defaultValue;
            // }
            if (!(value in mapping)) {
                this.reportError(new Error("Cannot find corresponding key for value \"" + value + "\". Available keys: " + Object.keys(mapping).join(', ')));
            }
            return mapping[value];
        };
        // _convertUsbData(appConfig: IAccessor): UsbConfig {
        //   let aliases: UsbAlias[] = [];
        //   let usbAliasesAcccessor = appConfig.get('USB_Aliases');
        //   for (let aliasNum = 0; ; aliasNum++) {
        //     let aliasName = `Alias${aliasNum}`;
        //     if (!usbAliasesAcccessor.has(aliasName)) {
        //       break;
        //     }
        //     let usbAliasRawData = hexStringToBuffer(usbAliasesAcccessor.value(aliasName));
        //     aliases.push(this._convertUsbAlias(usbAliasRawData));
        //   }
        //   return {
        //     aliases: aliases
        //   };
        // }
        // private _convertUsbAlias(data: Uint8Array): UsbAlias {
        //   return this.usbAliasConverter.decode(data);
        // }
        IoTizeStudioToTapConfigConverter.prototype.readProfilesConfig = function (profiles) {
            var results = [];
            for (var i = 0; i < profiles.length; i++) {
                var xmlProfile = profiles[i];
                var name = xmlProfile.value('Name');
                var profile = void 0;
                if (name === configurator.ANONYMOUS_USER.username) {
                    continue;
                }
                else if (configurator.isSpecialUser(name)) {
                    var specialConfig = {
                        username: xmlProfile.value('Name', 'string'),
                        lifeTime: xmlProfile.value('LifeTime', 'number', 0),
                        key: this.readUserKey(xmlProfile),
                    };
                    profile = specialConfig;
                }
                else {
                    var userConfig = {
                        username: xmlProfile.value('Name', 'string', ''),
                        id: xmlProfile.value('Id', 'number', 0),
                        lifeTime: xmlProfile.value('LifeTime', 'number', 0),
                        key: this.readUserKey(xmlProfile),
                    };
                    profile = userConfig;
                }
                var subProfilesConfig = xmlProfile.list('IOTizeUser', []);
                if (subProfilesConfig.length > 0) {
                    var subProfiles = this.readUserProfile(subProfilesConfig);
                    profile.users = subProfiles;
                }
                results.push(profile);
            }
            return results;
        };
        IoTizeStudioToTapConfigConverter.prototype.readUserKey = function (xmlProfile) {
            var scramPwd = xmlProfile.value('Scram_Pwd', 'string', undefined);
            if (scramPwd) {
                // let userSalt = xmlProfile.value('Scram_User_Salt', 'number');
                // specialConfig.salt = userSalt;
                return "0x" + scramPwd;
            }
            else {
                var key = xmlProfile.value('Pwd', 'string', undefined);
                if (key) {
                    return "0x" + key;
                }
            }
            return undefined;
        };
        IoTizeStudioToTapConfigConverter.prototype.readUserProfile = function (subProfilesConfig) {
            var users = [];
            for (var i = 0; i < subProfilesConfig.length; i++) {
                var xmlUserConfig = subProfilesConfig[i];
                var user = {
                    username: xmlUserConfig.value('Name', 'string', ''),
                    id: xmlUserConfig.value('Id', 'number', 0),
                    key: this.readUserKey(xmlUserConfig),
                };
                users.push(user);
            }
            return users;
        };
        IoTizeStudioToTapConfigConverter.prototype.readBundlesConfig = function (xmlBundles) {
            var result = [];
            for (var i = 0; i < xmlBundles.length; i++) {
                var xmlBundle = xmlBundles[i];
                var aclsXml = [];
                var aclContainer = xmlBundle.get('IOTizeAccessControl', undefined);
                if (aclContainer) {
                    aclsXml = aclContainer.list('IOTizeACL', []);
                }
                var acls = {};
                for (var j = 0; j < aclsXml.length; j++) {
                    var aclXml = aclsXml[j];
                    var profileName = aclXml.value('ProfileName');
                    if (profileName === configurator.ADMIN_USER.username) {
                        continue;
                    }
                    var rights = aclXml.value('Rights');
                    acls[profileName] = {
                        read: rights.includes('read'),
                        write: rights.includes('write'),
                    };
                }
                var bundleConfig = {
                    name: xmlBundle.value('GUI_Name'),
                    id: parseInt(xmlBundle.value('Id')),
                    variables: this.readVariablesConfig(xmlBundle.list('IOTizeVariable', [])),
                    acls: acls,
                    dataLog: {
                        period: xmlBundle.value('DataLogPeriod', 'number', 0),
                    },
                    features: this.readSpecialFeatures(xmlBundle.list('Feature', [])),
                };
                result.push(bundleConfig);
            }
            return result;
        };
        IoTizeStudioToTapConfigConverter.prototype.readSpecialFeatures = function (featuresXml) {
            if (featuresXml.length > 0) {
                var result = [];
                for (var i = 0; i < featuresXml.length; i++) {
                    var featureId = featuresXml[i].value('FeatureResId', 'number');
                    if (featureId in tap.SpecialFeature) {
                        var value = tap.SpecialFeature[featureId]; // TODO check
                        result.push(value);
                    }
                    else {
                        throw new Error("Unexpected feature id: " + featureId);
                    }
                }
                return result;
            }
            else {
                return undefined;
            }
        };
        IoTizeStudioToTapConfigConverter.prototype.readVariablesConfig = function (variables) {
            var result = [];
            for (var i = 0; i < variables.length; i++) {
                var xmlVariable = variables[i];
                var id = xmlVariable.value('Id', 'number');
                var length = xmlVariable.value('Quantity', 'number', 1);
                var dataType = toEnumType(convertToVariableType(xmlVariable), all.VariableType.Data);
                var name = xmlVariable.value('GUI_Name', 'string', '');
                var unit = xmlVariable.value('GUI_DispUnit', 'string', '') || undefined;
                var meta = void 0;
                if (name || unit) {
                    meta = {
                        name: name,
                        unit: unit,
                    };
                }
                var isInTapStatic = isTruthy(xmlVariable.value('IsInTap', 'string', '0'));
                var IsInTapVolatile = isTruthy(xmlVariable.value('IsInTapVolatile', 'string', '0'));
                if (IsInTapVolatile || isInTapStatic) {
                    var initialValueString = xmlVariable.value('InTap_InitialValueString', 'string', '');
                    var initialValue = decodeInitialVariableValue(initialValueString);
                    var inTapVariable = {
                        domain: IsInTapVolatile ? 'IN_TAP_VOLATIL' : 'IN_TAP_STATIC',
                        id: id,
                        length: length,
                        dataType: dataType,
                        meta: meta,
                        value: initialValue,
                    };
                    result.push(inTapVariable);
                }
                else {
                    // if (isModbusTargetConfig){
                    //     const modbusVariableConfig: ModbusVariableConfig = {
                    //         domain: 'TARGET',
                    //         modbusAddress: {
                    //         },
                    //         id,
                    //         length,
                    //         dataType,
                    //         name,
                    //         unit
                    //     };
                    //     result.push(variableConfig);
                    // }
                    // else {
                    var variableConfig = {
                        domain: 'TARGET',
                        address: toHexNumberConfig(xmlVariable.value('Address', 'number')),
                        id: id,
                        length: length,
                        dataType: dataType,
                        meta: meta,
                    };
                    result.push(variableConfig);
                    // }
                }
            }
            return result;
        };
        IoTizeStudioToTapConfigConverter.prototype._protocolDataToJsonConfig = function (protocolData, targetProtocolConfDataLen) {
            if (targetProtocolConfDataLen === 0) {
                return {
                    modbus: {
                        offsetFirstRegister: false,
                        slave: 0,
                    },
                    serial: {
                        baudRate: 115200,
                        bitParity: 'EVEN',
                        dataBits: '_8',
                        handshakeDelimiter: 'NONE',
                        hardwareFlowControl: 'NONE',
                        identification: false,
                        ledStatus: true,
                        physicalPort: 'AUTO',
                        stopBits: 'ONE',
                        timeout: 255,
                    },
                    usb: {
                        aliases: [],
                    },
                };
            }
            if (protocolData.length < 8) {
                throw IoTizeStudioError.invalidKeyValue('TargetProtocolConfData', // TODO change key
                'Protocol configuration data should be at least 8 bytes');
            }
            var ctr1 = protocolData.slice(0, 4);
            var ctr2 = protocolData.slice(4, 8);
            var remaining = protocolData.slice(8);
            //  KaitaiStreamWriter.mergeArrays(ctr2, ctr1).reverse(),
            protocolData = byteStream.KaitaiStreamWriter.mergeArrays(ctr1.reverse(), ctr2.reverse(), remaining);
            var PROTOCOL_CONF_CTR_LENGHT = 8;
            var reorderedProtocolData = byteStream.KaitaiStreamWriter.mergeArrays(protocolData.slice(0, PROTOCOL_CONF_CTR_LENGHT).reverse(), protocolData.slice(PROTOCOL_CONF_CTR_LENGHT));
            var protocolConf = all.tapnpassConverters.tapnpassProtocolConfiguration.decode(reorderedProtocolData);
            var serial = protocolConf.serial;
            var usb = protocolConf.usb;
            return {
                modbus: protocolConf.modbus,
                serial: {
                    baudRate: serial.baudRate,
                    bitParity: this.toEnumKey(serial.bitParity, all.SerialSettings.BitParity),
                    dataBits: this.toEnumKey(serial.dataBits, all.SerialSettings.DataBits),
                    handshakeDelimiter: this.toEnumKey(serial.handshakeDelimiter, all.SerialSettings.HandshakeDelimiter),
                    hardwareFlowControl: this.toEnumKey(serial.hardwareFlowControl, all.SerialSettings.HardwareFlowControl),
                    physicalPort: this.toEnumKey(serial.physicalPort, all.SerialSettings.PhysicalPort),
                    stopBits: this.toEnumKey(serial.stopBits, all.SerialSettings.StopBits),
                    timeout: serial.timeout,
                    identification: false,
                    ledStatus: false,
                },
                usb: usb,
            };
        };
        return IoTizeStudioToTapConfigConverter;
    }());
    function toHexNumberConfig(v) {
        return '0x' + v.toString(16);
    }

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

    exports.BundleDoesNotExistError = BundleDoesNotExistError;
    exports.InvalidConfigurationError = InvalidConfigurationError;
    exports.IoTizeStudioToTapConfigConverter = IoTizeStudioToTapConfigConverter;
    exports.IotizeBundleModel = IotizeBundleModel;
    exports.IotizeConfigFactory = IotizeConfigFactory;
    exports.IotizeConfigModel = IotizeConfigModel;
    exports.IotizeProfileModel = IotizeProfileModel;
    exports.IotizeVariableModel = IotizeVariableModel;
    exports.VariableDoesNotExistError = VariableDoesNotExistError;
    exports.convertIoTizeStudioConfigToTapConfig = convertIoTizeStudioConfigToTapConfig;

    Object.defineProperty(exports, '__esModule', { value: true });

}));
//# sourceMappingURL=iotize-tap-config-iotize-studio.umd.js.map
