"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("../../../../core");
var multiple_mask_decoder_1 = require("./multiple-mask-decoder");
var number_decoder_1 = require("./number-decoder");
var logger_1 = require("../../../../logger");
var logger = logger_1.default('Converter');
/**
 * TODO improv it . We don't know the size of input buffer...
 */
var UniqMaskConverter = /** @class */ (function () {
    // protected _reverseMapping: { [key: number]: OutputType };
    function UniqMaskConverter(mapping) {
        this._mapping = mapping;
    }
    UniqMaskConverter.prototype.decode = function (body) {
        return UniqMaskConverter.decodeOne(body, this._mapping);
    };
    UniqMaskConverter.prototype.encode = function (value) {
        return UniqMaskConverter.encodeOneAsBuffer(value, this._mapping);
    };
    UniqMaskConverter.decodeOneExact = function (data, mapping) {
        if (typeof data !== "number") {
            data = number_decoder_1.NumberConverter.fromOpaqueMsb(data);
        }
        for (var key in mapping) {
            var mask = parseInt(key);
            if (data == mask) {
                return mapping[mask];
            }
        }
        throw new Error("Cannot decode " + (typeof data === "number" ? 'number ' + data : '0x' + core_1.FormatHelper.toHexString(data)) + ". Available keys are " + Object.keys(mapping));
    };
    UniqMaskConverter.decodeOne = function (data, mapping) {
        var results = multiple_mask_decoder_1.MultipleMaskConverter.decodeAll(data, mapping);
        if (results.length == 0) {
            throw new Error("Cannot decode value " + (typeof data === "number" ? data : '0x' + core_1.FormatHelper.toHexString(data)) + ". Available keys are " + Object.keys(mapping));
        }
        else if (results.length > 1) {
            logger.warn("Multiple result for data : ", results, data, mapping);
        }
        return results[0];
    };
    UniqMaskConverter.encodeOneAsNumber = function (data, mapping) {
        var swappedMap = UniqMaskConverter.swapKeyValue(mapping);
        var dataAsString = data.toString();
        if (!(dataAsString in swappedMap)) {
            throw new Error("Key " + dataAsString + " does not exist in mapping. Available keys are " + Object.keys(swappedMap));
        }
        return parseInt(swappedMap[dataAsString]);
    };
    UniqMaskConverter.encodeOneAsBuffer = function (data, mapping) {
        var result = new Uint8Array(1); // TODO change according to conf
        var encodedValue = UniqMaskConverter.encodeOneAsNumber(data, mapping);
        result[0] = encodedValue & 0xFF;
        return result;
    };
    UniqMaskConverter.swapKeyValue = function (input) {
        var ret = {};
        for (var key in input) {
            ret[input[key]] = key;
        }
        return ret;
    };
    return UniqMaskConverter;
}());
exports.UniqMaskConverter = UniqMaskConverter;
