class Connection {
    connectionTries = 0
    ws;
    linkCreated;
    wsStatus;

    constructor(receiveCB) {
        this.init()
        this.receiveCB = receiveCB
    }
    
    init() {
        if(window.location.hostname === "localhost") {
            this.ws = new WebSocket("ws://" + "localhost:3003")
        } else {
            this.ws = new WebSocket("wss://" + window.location.hostname + window.location.pathname)
        }
        this.ws.addEventListener('open', () => {
            this.connectionTries = 0
            console.log("Websocket connection established.");
            this.ws.addEventListener('message', this.receiveCB)
        });
        this.ws.addEventListener("close", () => {
            this.checkOpen();
            console.log('Websocket Closed')
        })
    }
    
    async checkOpen() {
        if (this.ws.readyState === WebSocket.OPEN) {
            return true
        } else {
            await this.sleep(this.connectionTries < 20 ? 5000 : 60000)
            this.connectionTries++
            console.log('Reestablishing connection')
            this.init()
        }
    }

    sleep = (time) => {
        return new Promise(resolve => {
            setTimeout(resolve, time);
        });
    }
    
    send = (msg) => {
        console.log("sending")
        if (this.ws.readyState === WebSocket.OPEN) {
            this.ws.send(msg);
        }
        else if(this.connectionTries === 0) {
            setTimeout(() => {
                this.send(msg)
            }, 100)
        }
        else {
            console.error('No websocket connection: Cannot send message');
        }
    }
}

export default Connection