"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MotionMasterPubSubWorkerSocket = void 0;
const rxjs_1 = require("rxjs");
const logger_1 = require("./logger");
class MotionMasterPubSubWorkerSocket {
    constructor(worker) {
        this.worker = worker;
        this.opened$ = new rxjs_1.BehaviorSubject(false);
        this.close$ = new rxjs_1.Subject();
        this.data$ = new rxjs_1.Subject();
    }
    get url() {
        return this._url;
    }
    open(url) {
        this._url = url;
        this.worker.onmessage = ({ data }) => {
            if ('opened' in data) {
                const { opened } = data;
                this.opened$.next(opened);
                logger_1.logger.info(opened ? `Opened pub/sub 🔌 ${url}` : `Closed pub/sub 🔌 ${url}`);
            }
            else if ('topic' in data) {
                const { topic, messages } = data;
                messages.forEach((message) => this.data$.next([topic, message]));
            }
            else if ('close' in data) {
                const { close } = data;
                this.close$.next(close);
                logger_1.logger.info(`Close event received on pub/sub 🔌 ${url} ${JSON.stringify(close)}`);
            }
        };
        this.worker.postMessage({
            open: { url },
        });
    }
    close() {
        this.worker.postMessage({ close: true });
    }
    reopen() {
        if (this.url && this.opened$.value === false) {
            this.open(this.url);
        }
    }
}
exports.MotionMasterPubSubWorkerSocket = MotionMasterPubSubWorkerSocket;
//# sourceMappingURL=motion-master-pub-sub-worker-socket.js.map