import Connection from "./Connection.js";

export default class Socket {
    connection;
    disabled = true;
    requestID = 1;
    pending = new Map();

    constructor() {
        this.connection = new Connection(this.receive);
    }

    async init() {
        await this.connection.init()
    }

    isOpen() {
        if(this.connection.checkOpen()) {
            return true;
        } else {
            return false;
        }
    }

    send(msg) {
        return new Promise(resolve => {
            const id = (++this.requestID).toString();
            this.pending.set(id, resolve);
            this.connection.send(JSON.stringify({ id, ...msg }));
        });
    }

    receive = (event) => {
        const msg = JSON.parse(event.data);
        if (msg.id && this.pending.has(msg.id)) {
            this.pending.get(msg.id)(msg);
            this.pending.delete(msg.id);
            return;
        } else {
            this.onBroadcast(msg)
        }
    }

    onBroadcast(msg) {
        window.dispatchEvent(new CustomEvent(msg.event, {
            detail: msg.msg
        }));
    }
}