import {getGlobal} from "../../source/types/global.mjs";

function initWebSocket() {

    class MockWebSocket {
        constructor(url) {
            this.url = url;
            this.readyState = 0;
            setTimeout(() => {
                this.readyState = 1;
                if (typeof this.onopen === "function") {
                    this.onopen();
                }
            }, 0);
        }

        send(data) {
            if (this.readyState !== 1) {
                return;
            }
            setTimeout(() => {
                if (typeof this.onmessage === "function") {
                    this.onmessage({data});
                }
            }, 0);
        }

        close() {
            if (this.readyState === 3) {
                return;
            }
            this.readyState = 3;
            if (typeof this.onclose === "function") {
                this.onclose({code: 1000});
            }
        }

        terminate() {
            this.close();
        }
    }

    getGlobal().WebSocket = MockWebSocket;
    return Promise.resolve();


}

export {initWebSocket}
