"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tap_stream_1 = require("../frame/tap-stream");
var Header = /** @class */ (function () {
    function Header(path, resourceInstance) {
        if (resourceInstance === void 0) { resourceInstance = undefined; }
        this.path = path;
        this.resourceInstance = resourceInstance;
    }
    Header.prototype.getResourceInstance = function () {
        return this.resourceInstance;
    };
    Header.prototype.getPath = function () {
        return "/" + this.path.objectId + "/" + (this.path.objectInstanceId == Header.MAX_ID ? '' : this.path.objectInstanceId) + "/" + this.path.resourceId + (this.resourceInstance ? '/' + this.resourceInstance : '');
    };
    Object.defineProperty(Header.prototype, "objectId", {
        get: function () {
            return this.path.objectId;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Header.prototype, "objectInstance", {
        get: function () {
            return this.path.objectInstanceId;
        },
        enumerable: true,
        configurable: true
    });
    Object.defineProperty(Header.prototype, "resourceId", {
        get: function () {
            return this.path.resourceId;
        },
        enumerable: true,
        configurable: true
    });
    Header.fromBytes = function (bytes) {
        var path = tap_stream_1.TapStreamReader.fromArray(bytes).readTapRequestPath();
        var header = new Header(path);
        if (bytes.length == 8) {
            // What is that ???
            header.resourceInstance = ((bytes[6] << 8) & Header.MAX_ID) + (bytes[7] & 0xFF);
            header.resourceInstance &= Header.MAX_ID;
        }
        // return header; 
        return header;
    };
    Header.fromString = function (command) {
        if (command == null || command.length == 0) {
            throw new Error("Invalid command: null");
        }
        command = command.trim();
        var result = command.match(Header.PATH_EXPRESSION);
        if (!result || result.length === 0) {
            throw new Error("Invalid header \"" + command + "\". Format is invalid"); // TODO better error
        }
        var header = new Header({
            objectId: this.validateId(parseInt(result[1])),
            objectInstanceId: result[2] ? parseInt(result[2]) : 0xFFFF,
            resourceId: parseInt(result[3])
        }, result[4] ? parseInt(result[4]) : undefined);
        return header;
    };
    Header.validateId = function (id) {
        if (id < 0 || id > Header.MAX_ID) {
            throw new Error("Invalid identifier \"" + id + "\". It must be a number between " + id + " and " + Header.MAX_ID);
        }
        return id;
    };
    // TODO move to config global
    Header.PATH_EXPRESSION = /^\/?([0-9]+)\/([0-9]+)?\/([0-9]+)\/?([0-9]+)?$/;
    Header.MAX_ID = 0xFFFF;
    return Header;
}());
exports.Header = Header;
