"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MotionMasterReqResWorkerSocket = void 0;
const rxjs_1 = require("rxjs");
const logger_1 = require("./logger");
const util_1 = require("./util");
class MotionMasterReqResWorkerSocket {
    constructor(worker) {
        this.worker = worker;
        this.opened$ = new rxjs_1.BehaviorSubject(false);
        this.close$ = new rxjs_1.Subject();
        this.alive$ = new rxjs_1.BehaviorSubject(false);
        this.message$ = new rxjs_1.Subject();
    }
    get url() {
        return this._url;
    }
    get pingSystemInterval() {
        return this._pingSystemInterval;
    }
    get systemAliveTimeout() {
        return this._systemAliveTimeout;
    }
    open(url, pingSystemInterval = 250, systemAliveTimeout = 1000) {
        this._url = url;
        this._pingSystemInterval = pingSystemInterval;
        this._systemAliveTimeout = systemAliveTimeout;
        this.worker.onmessage = ({ data }) => {
            if ('opened' in data) {
                const { opened } = data;
                this.opened$.next(opened);
                logger_1.logger.info(opened ? `Opened req/res 🔌 ${url}` : `Closed req/res 🔌 ${url}`);
            }
            else if ('alive' in data) {
                const { alive } = data;
                this.alive$.next(alive);
                logger_1.logger.info(alive ? `System is alive 💓` : 'System is as dead as 🦤');
            }
            else if ('message' in data) {
                const { message } = data;
                const context = (0, util_1.convertMotionMasterMessageToLoggerContext)(message);
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                logger_1.logger.info(context, `Received ${context.name}`);
                this.message$.next(message);
            }
            else if ('close' in data) {
                const { close } = data;
                this.close$.next(close);
                logger_1.logger.info(`Close event received on req/res 🔌 ${url} ${JSON.stringify(close)}`);
            }
        };
        this.worker.postMessage({
            open: { url, pingSystemInterval, systemAliveTimeout },
        });
    }
    reopen() {
        if (this.url && this.opened$.value === false) {
            this.open(this.url, this.pingSystemInterval, this.systemAliveTimeout);
        }
    }
    close() {
        this.worker.postMessage({ close: true });
    }
    send(message) {
        const context = (0, util_1.convertMotionMasterMessageToLoggerContext)(message);
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        logger_1.logger.info(context, `Send ${context.name}`);
        this.worker.postMessage({ message });
    }
}
exports.MotionMasterReqResWorkerSocket = MotionMasterReqResWorkerSocket;
//# sourceMappingURL=motion-master-req-res-worker-socket.js.map