import { apiPort } from './api.js';

let singleton = false;

export class WS {

    constructor(){
        console.log("starting new websocket")
        if (singleton && singleton.open) {
            return singleton;
        }

        const endpoint = `ws://localhost:2015/ws`;
        this.conn = new WebSocket(endpoint);
        this.conn.onerror = this.onerror();
        this.conn.onclose = this.onclose();
        this.conn.onmessage = this.onmessage();
        this.conn.onopen = this.onopen();
    }

    send(data) {
        this.conn.send(data);
    }

    onopen(){
        let self = this;
        return (ev) => {
            self.opened = true;
            console.log("websocket opened");
        }
    }

    onerror (){
        let self = this;
        return (ev) => {
            console.error(ev);
        }
    }

    onclose () {
        let self = this;
        let instance = singleton
        return (ev) => {
            console.warn("websocket closed");
            //TODO: restore on prod
            //setTimeout(() =>{
                //console.log("websocket: trying to reconnect")
                //instance = new WS()
            //}, 3000)
        }
    }

    onmessage() {
        let self = this;

        return (ev) => {
            let msg = JSON.parse(ev.data);

            switch (msg.type) {
                case 'hello':
                    console.log(msg.data);
                    break;

                case 'upload-accepted':
                    console.log(msg)
                    break;
            }
        }

    }

}

