import DatabaseProperty from "./Database/DatabaseProperty";
import BadDataException from "./Exception/BadDataException";
import { ObjectType } from "./JSON";
import PositiveNumber from "./PositiveNumber";
import Typeof from "./Typeof";
import Zod from "../Utils/Schema/Zod";
export default class Port extends DatabaseProperty {
    get port() {
        return this._port;
    }
    set port(value) {
        if (Port.isValid(value)) {
            this._port = value;
        }
        else {
            throw new BadDataException("Port is not in valid format.");
        }
    }
    toJSON() {
        return {
            _type: ObjectType.Port,
            value: this.toNumber(),
        };
    }
    static fromJSON(json) {
        if (json["_type"] === ObjectType.Port) {
            return new Port(json["value"] || "");
        }
        throw new BadDataException("Invalid JSON: " + JSON.stringify(json));
    }
    static isValid(port) {
        if (typeof port === Typeof.String) {
            try {
                port = Number.parseInt(port.toString().trim(), 10);
            }
            catch (_a) {
                return false;
            }
        }
        if (port instanceof PositiveNumber) {
            port = port.toNumber();
        }
        if (port >= 0 && port <= 65535) {
            return true;
        }
        return false;
    }
    constructor(port) {
        super();
        this._port = new PositiveNumber(0);
        this.port = new PositiveNumber(port);
    }
    static toDatabase(value) {
        if (typeof value === "string") {
            value = new Port(value);
        }
        if (value instanceof Port) {
            return value.toNumber();
        }
        else if (typeof value === "string") {
            return parseInt(value);
        }
        return null;
    }
    static fromDatabase(_value) {
        if (_value) {
            return new Port(_value);
        }
        return null;
    }
    toString() {
        return this.port.toString();
    }
    toNumber() {
        return this.port.toNumber();
    }
    static getSchema() {
        return Zod.object({
            _type: Zod.literal(ObjectType.Port),
            value: Zod.number().int().min(0).max(65535).openapi({
                type: "number",
                example: 8080,
            }),
        }).openapi({
            type: "object",
            description: "Port object",
            example: { _type: ObjectType.Port, value: 8080 },
        });
    }
}
//# sourceMappingURL=Port.js.map