"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "WebsocketAdapter", {
    enumerable: true,
    get: function() {
        return WebsocketAdapter;
    }
});
const _serverconstants = require("../server.constants");
const _ws = require("ws");
class WebsocketAdapter {
    socket;
    logger;
    eventEmittingAllowed = true;
    constructor(loggerFactory){
        this.logger = loggerFactory(WebsocketAdapter.name);
    }
    get isOpened() {
        return this.socket?.readyState === _ws.WebSocket.OPEN;
    }
    close() {
        this.socket?.close();
        delete this.socket;
    }
    allowEmittingEvents() {
        this.eventEmittingAllowed = true;
    }
    disallowEmittingEvents() {
        this.eventEmittingAllowed = false;
    }
    open(url) {
        if (!url) {
            throw new Error("Cant setup up websocket, URL may not be empty.");
        }
        this.socket = new _ws.WebSocket(url, {
            handshakeTimeout: _serverconstants.AppConstants.defaultWebsocketHandshakeTimeout
        });
        this.socket.onopen = (event)=>this.onOpen(event);
        this.socket.onerror = (error)=>this.onError(error);
        this.socket.onclose = (event)=>this.onClose(event);
        this.socket.onmessage = (message)=>this.onMessage(message.data);
    }
    async sendMessage(payload) {
        if (!this.isOpened || !this.socket) {
            this.logger.error("Websocket is not opened, cant send a message");
            return;
        }
        return await new Promise((resolve, reject)=>{
            this.socket.send(payload, (error)=>{
                if (error) reject(error);
                resolve();
            });
        });
    }
    async onOpen(event) {
        await this.afterOpened(event);
    }
    async onClose(event) {
        await this.afterClosed(event);
    }
}

//# sourceMappingURL=websocket.adapter.js.map