var startTime = Date.now() ;
console.log("Meine Document-Location: " + document.location);
var lastPingRequest;

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

var socket = new WebSocket(String(document.location).replace("https://","wss://").replace("1003","2095").replace("index.html","") + "echo");
socket.onopen = () => console.log('Connected') ||  setInterval(() => {  lastPingRequest = Date.now();
                                                                        socket.send("Ping");
                                                                     }, 5000);    
socket.onclose = (event) =>  console.log((event.wasClean) ? 'Disconnected' :  'Connection break: ' + (event.reason || event.code)); 

socket.onmessage = (event) => {
    if(event.data == "Ping"){
        console.log("Ping: " + (Date.now() - lastPingRequest).toString() + " ms");
    }
    else if(isJson(event.data.toString())){
        const obj = JSON.parse(event.data.toString()); 
        robot.receiveCoordinates(obj)
        console.log(obj);
        robot.showRobot();
    }
    else{
        console.log("xyt");
        console.log('DATA  SinceStartup: ' +  (Date.now() - startTime).toString() +':  ', event.data);
    }
}

socket.onerror = (err) => console.error(err.message);


