const dynDiv = document.getElementById("dynDiv");
var sentMessage = false;
var counter = 0;

function watchSSE() {
    // SSE events if supported
    if(typeof(EventSource) !== "undefined") {
        var source = new EventSource("watcher.php");
        source.onmessage = function(event) {
            // Clear log after 15 intervals
            if (counter == 15) {
                dynDiv.innerHTML = "";
                counter = 0;
            }

            if (event.data === "true") {
                // Server is down b/c return is true
                if (sentMessage) {
                    dynDiv.innerHTML += "<p class='error'>Server is Down.... Messages already sent.</p>";
                } else {
                    sentMessage = true;
                    dynDiv.innerHTML += "<p class='error'>Server is Down.... Sending messages...</p>";
                    sendMessage();
                }
            } else if (event.data === "networkDown") {
                sentMessage = false;
                dynDiv.innerHTML += "<p class='error'>Local network is down...</p>";
            } else {
                // Server is not down b/c return is false
                sentMessage = false;
                dynDiv.innerHTML += "<p class='success'>Up...</p>";
            }
            counter++;
        };
    } else { console.log("SSE Not Supported In Browser..."); }
}

function sendMessage() {
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "sendMessage.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("sendMessage=true");
}
