"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tlv_converter_1 = require("../../client/impl/converter/tlv-converter");
var buffer_1 = require("buffer");
var TlvBundleConverter = /** @class */ (function () {
    function TlvBundleConverter(variables, tlvConverter) {
        if (variables === void 0) { variables = []; }
        if (tlvConverter === void 0) { tlvConverter = new tlv_converter_1.TLVConverter(); }
        this.variables = variables;
        this.tlvConverter = tlvConverter;
    }
    TlvBundleConverter.prototype.decode = function (data, context) {
        if (data instanceof Uint8Array) {
            var buffer = buffer_1.Buffer.from(data.buffer);
            data = this.tlvConverter.decode(buffer);
        }
        var result = this._converteTlvTree(data);
        return result;
    };
    /**
     * TODO
     */
    TlvBundleConverter.prototype.encode = function (data) {
        throw new Error("Not implemented yet");
    };
    /**
     * Converter tlv tree to variable name => value
     */
    TlvBundleConverter.prototype._converteTlvTree = function (tree, variableMeta) {
        var result = {};
        // Recursive call to decode children 
        if (tree.children) {
            result = {};
            var _loop_1 = function (child) {
                var variableMetas = this_1.variables.filter(function (v) { return v.id == child.header.id; });
                if (variableMetas.length == 0) {
                    variableMetas.push({
                        id: child.header.id
                    });
                }
                for (var _i = 0, variableMetas_1 = variableMetas; _i < variableMetas_1.length; _i++) {
                    var variableMeta_1 = variableMetas_1[_i];
                    var key = (variableMeta_1 && variableMeta_1.name) ? variableMeta_1.name : child.header.id.toString();
                    result[key] = this_1._converteTlvTree(child, variableMeta_1);
                }
            };
            var this_1 = this;
            for (var _i = 0, _a = tree.children; _i < _a.length; _i++) {
                var child = _a[_i];
                _loop_1(child);
            }
        }
        // Decode current node
        else if (tree.payload) {
            var converter = variableMeta ? variableMeta.converter : undefined;
            if (converter) {
                result = converter.decode(tree.payload);
            }
            else {
                result = Uint8Array.from(tree.payload);
            }
        }
        return result;
    };
    return TlvBundleConverter;
}());
exports.TlvBundleConverter = TlvBundleConverter;
