"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const ws_1 = require("ws");
const rxjs_1 = require("rxjs");
const stringify = require("json-stringify-safe");
class WebSocketBus {
    constructor(port = 8080) {
        this.port = port;
        this.receiver = new rxjs_1.Subject();
        this.sender = new rxjs_1.Subject();
    }
    startServer() {
        this.ws = new ws_1.Server({ port: this.port });
        this.ws.on("open", this.onConnectionOpen);
        this.ws.on("close", this.onConnectionClosed);
        return this;
    }
    init(requests) {
        this.requests = requests;
        this.ws.on("connection", (ws) => {
            this.sender.subscribe((a) => {
                ws.send(JSON.stringify(a));
            });
            ws.on("message", message => this.onMessageReceived.call(this, message, ws));
        });
        return this;
    }
    sendMessage(message) {
        this.sender.next(message);
    }
    listen() {
        return this.receiver.asObservable();
    }
    close() {
        this.ws.close();
    }
    onConnectionOpen() {
        console.log("conneted");
    }
    onConnectionClosed() {
        console.log("disconneted");
    }
    async onMessageReceived(message, ws) {
        const data = JSON.parse(message);
        this.receiver.next(data);
        if (!this.requests[data.REQUEST])
            return;
        const response = await this.requests[data.REQUEST](data.PAYLOAD);
        if (response)
            ws.send(stringify(response));
    }
}
exports.WebSocketBus = WebSocketBus;
