import store from './store'

var ws = null;
// var wsState = false;

export function getWsState() {
    // return wsState;
    return store.state.wsState;
}

function setWsState(wsState) {
    store.commit('setWsState', wsState);
}

export function connect(wsUrl, wsId) {
    if (ws != null) {
        return true;
    }

    if (wsUrl == '' || wsId == '') {
        console.log("[WebSocket] Connection err: param err"); 
        return false;
    }

    let url = wsUrl + '/' + wsId;
    ws = new WebSocket(url);
    console.log("[WebSocket] exec connect(" + url + ")");

    ws.onopen = function(evt) {
        setWsState(true);
        console.log("[WebSocket] Connection open: " + JSON.stringify(evt)); 
        // ws.send("Hello WebSockets!");
    };

    ws.onmessage = (evt) => {
        // var data = evt.data;
        console.log("[WebSocket] message: " + JSON.stringify(evt));
        // ws.send('ping');
      };

    ws.onclose = function(evt) {
        ws = null;
        setWsState(false);
        console.log("[WebSocket] Connection closed.");
    };

    ws.onerror = function(evt) {
        console.log("[WebSocket] error: " + JSON.stringify(evt));
        disconnect();
        setWsState(false);
    };

    return true;
}

export function disconnect() {
    console.log("[WebSocket] exec disconnect()");
    if (ws != null && ws.readyState == WebSocket.OPEN) {
        ws.close();
        console.log("[WebSocket] exec ws.close()");
        ws = null;
    }
}

export function sendData(data) {
    if (getWsState()) {
        ws.send(data);
        // console.log("[WebSocket] sendData: " + data);
        return true;
    }
    else {
        console.log("[WebSocket] sendData err: " + data);
        return false;
    }
}

