import DatabaseProperty from "../Database/DatabaseProperty";
import BadDataException from "../Exception/BadDataException";
import { ObjectType } from "../JSON";
import Port from "../Port";
import Typeof from "../Typeof";
export default class Hostname extends DatabaseProperty {
    get hostname() {
        return this._route;
    }
    get port() {
        return this._port;
    }
    set port(v) {
        this._port = v;
    }
    set hostname(value) {
        value = value.trim();
        if (Hostname.isValid(value)) {
            this._route = value;
        }
        else {
            throw new BadDataException("Hostname " + value + " is not in valid format.");
        }
    }
    static isValid(value) {
        const re = /^[a-zA-Z-\d!#$&'*+,/:;=?@[\].]*$/;
        const isValid = re.test(value);
        if (!isValid) {
            return false;
        }
        return true;
    }
    constructor(hostname, port) {
        super();
        this._route = "";
        if (hostname) {
            this.hostname = hostname;
        }
        if (port instanceof Port) {
            this.port = port;
        }
        else if (typeof port === Typeof.String) {
            this.port = new Port(port);
        }
        else if (typeof port === Typeof.Number) {
            this.port = new Port(port);
        }
    }
    toJSON() {
        return {
            _type: ObjectType.Hostname,
            value: this.toString(),
        };
    }
    static fromJSON(json) {
        if (json["_type"] === ObjectType.Hostname) {
            return new Hostname(json["value"] || "");
        }
        throw new BadDataException("Invalid JSON: " + JSON.stringify(json));
    }
    toString() {
        let hostname = this.hostname;
        if (this.port) {
            hostname += ":" + this.port.toString();
        }
        return hostname;
    }
    static fromString(hostname) {
        if (hostname instanceof Hostname) {
            hostname = hostname.toString();
        }
        if (hostname.includes(":")) {
            return new Hostname(hostname.split(":")[0], hostname.split(":")[1]);
        }
        return new Hostname(hostname);
    }
    static toDatabase(value) {
        if (value) {
            if (typeof value === "string") {
                value = new Hostname(value);
            }
            return value.toString();
        }
        return value;
    }
    static fromDatabase(_value) {
        if (_value) {
            return new Hostname(_value);
        }
        return null;
    }
}
//# sourceMappingURL=Hostname.js.map