"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tlv_converter_1 = require("../../client/impl/converter/tlv-converter");
var variable_1 = require("../target-variable/variable");
var TlvBundleConverter = /** @class */ (function () {
    function TlvBundleConverter(variableMapping, tlvConverter) {
        if (tlvConverter === void 0) { tlvConverter = new tlv_converter_1.TLVConverter(); }
        this.variableMapping = variableMapping;
        this.tlvConverter = tlvConverter;
    }
    TlvBundleConverter.prototype.decode = function (data, context) {
        var buffer = Buffer.from(data);
        // console.debug("RAW BODY: ", buffer);
        var tlvTree = this.tlvConverter.decode(buffer);
        console.debug('Bundle', 'Variable data: ', tlvTree);
        // Decode variables
        var result = this._converteTlvTree(tlvTree);
        return result;
    };
    /**
     * TODO
     */
    TlvBundleConverter.prototype.encode = function (data) {
        throw new Error("Not implemented yet");
    };
    /**
     * Converter tlv tree to id => value
     */
    TlvBundleConverter.prototype._converteTlvTree = function (tree, variableIdentifier) {
        var result = {};
        // Recursive call to decode children 
        if (tree.children) {
            result = {};
            for (var _i = 0, _a = tree.children; _i < _a.length; _i++) {
                var child = _a[_i];
                var key = void 0;
                if (this.variableMapping) {
                    key = this.variableMapping.getById(child.header.id).identifier();
                }
                else {
                    key = child.header.id.toString();
                }
                result[key] = this._converteTlvTree(child, key);
            }
        }
        // Decode current node
        else if (tree.payload) {
            var converter = variableIdentifier ? this.getConverterFromVariableIdentifier(variableIdentifier) : undefined;
            if (converter) {
                result = converter.decode(tree.payload);
            }
            else {
                result = Uint8Array.from(tree.payload);
            }
        }
        return result;
    };
    TlvBundleConverter.prototype.getConverterFromVariableIdentifier = function (variableIdentifier) {
        if (this.variableMapping && variableIdentifier) {
            var variable = this.variableMapping.get(variableIdentifier);
            if (variable instanceof variable_1.VariableConfig) {
                return variable.converter;
            }
        }
        return undefined;
    };
    return TlvBundleConverter;
}());
exports.TlvBundleConverter = TlvBundleConverter;
