
function checkIfUpdateRan() {  // runs when startup loads to check if update was just finished
    if (updateAvailable >= 2) {  // load update finished confirmation if necessary
        // updateAvailable = 4;
        var command = "992";
        sendToBackend(command);  // tell backend frontend has notified user update is complete
        $('#popupBackground').show();  // grey out background
        $('.ds18b20Popup-body').empty();
        ds18b20Popup.style.display = "block";
        document.querySelector("body").style.overflow = 'hidden';
        $('.ds18b20PopupHeader').empty();
    
        $(".ds18b20PopupHeader").append("Robo-Tank Update Finished");
        $(".ds18b20Popup-body").append(
            `<div style="text-align: center;">\
                <p>&nbsp;</p>\
                <p style="font-weight:bold">You are now running Robo-Tank version ` + latestVersion + `!</p>\
                <p style="font-weight:bold; color:#FF0000;">Important - You need to clear your browser cache if haven't already!</p>\
                <p>* You can clear the browser cache by pressing <b>CTRL + SHIFT + R</b> on your keyboard, Click OK below before doing this.</p>\
                <p style="font-weight:bold; color:#FF0000;">Click OK to continue, you will be logged out!</p>\
                <div class="widgetButtonBox">\
                    <button class="button _wide" type="button" onclick="updateFinished()">Ok</button>\
                </div></br>\
            </div>`);
        
    }
    // else {closeDs18b20Popup();}
}

function updateFinished() {  // update finished
    closeDs18b20Popup();
    location.reload(true);
    window.location.href = window.location.href;
    window.location.href = 'logout.php';
}

function manualUpdate() {  // manually check for update
    if (autoUpdate == 0) {
        var command = "994";
        sendToBackend(command);
    }
}

function checkForUpdate() {  // check for software update
    // console.log('checkForUpdate ---------------------- ' + updateAvailable);

    var divExists = document.getElementById("updateIconContainer");  // check if div is drawn
    if(divExists){
        if (updateAvailable == 1) {  // if update available draw link and update button on system settings page
            document.getElementById('updateIconBox').innerHTML = 'Install Version ' + latestVersion + '<span class="updateIcon bi bi-cloud-arrow-down-fill"></span>';

            document.getElementById('updateIconContainer').style.display = "block";
            document.getElementById('headerDatetime').style.float = "right";
            document.getElementById('updateIconBox').innerHTML = 'Install Version ' + latestVersion + '<span class="updateIcon bi bi-cloud-arrow-down-fill"></span>';
            
            if (displayScreen == 8) {  // if viewing the system settings page update button                
                document.getElementById('manualUpdateButton').onclick = runUpdate;
                document.getElementById('manualUpdateButton').innerHTML = "Install Version " + latestVersion;
                document.getElementById('manualUpdateButton').style.backgroundColor = "#00FF00";
                document.getElementById('manualUpdateButton').style.color = "#000000";
            }

            if (updateReady == 0) {  // only read database once to get new version. When we install update it'll check again
                $.ajax({
                    url: "/php/getLatestVersion.php",
                    method: "GET",
                    cache: false,
                    success: function(dataWindow) {
                        console.log("getLatestVersion--------------------------------------------------------------");
                        appVersion = (dataWindow[0].version);  // version running
                        latestVersion = (dataWindow[0].versionLatest);  // latest version
                        console.log('appVersion     = ' + appVersion);
                        console.log('latestVersion  = ' + latestVersion);

                    },
                    error: function(dataWindow) {
                        console.log(dataWindow);
                        console.log('error - getLatestVersion');
                    }
                });
            }
            updateReady = 1;
        }
        else if (updateAvailable == 2) {  // when backend is finished update this will tell backend front end has reloaded and showing confirmation, this finishes the process on backend
            var command = "991";
            sendToBackend(command);
            location.reload(true);
        }
        else {  // hide update link if not needed
            document.getElementById('updateIconContainer').style.display = "none";
            document.getElementById('headerDatetime').style.float = "none";
        }
    }
}

function runUpdate() {
    console.log("runUpdate--------------------------------------------------------------");
    $.ajax({  // before update check for latest version just incase another update was released after setting initial update ready flag
        url: "/php/getLatestVersion.php",
        method: "GET",
        cache: false,
        success: function(dataWindow) {
            console.log("getLatestVersion--------------------------------------------------------------");
            appVersion = (dataWindow[0].version);  // version running
            latestVersion = (dataWindow[0].versionLatest);  // latest version
            console.log('appVersion     = ' + appVersion);
            console.log('latestVersion  = ' + latestVersion);
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - getLatestVersion');
        }
    });

    $('#popupBackground').show();  // grey out background
    $('.ds18b20Popup-body').empty();
    ds18b20Popup.style.display = "block";
    document.querySelector("body").style.overflow = 'hidden';
    $('.ds18b20PopupHeader').empty();

    $(".ds18b20PopupHeader").append("Robo-Tank Update Available");
    $(".ds18b20Popup-body").append(
        `<div style="text-align: center;">\
            <p>&nbsp;</p>\
            <p style="font-weight:bold">Robo-Tank version ` + latestVersion + ` is ready!</p>\
            <p>This update should take less than a minute to complete, would you like to continue?</br>\
            <span style="font-style: italic;">(make sure the app is only running in one browser or device before starting the update)</span></p>\
            <p style="font-weight:bold; color:#FF0000;">Important - When the update is finished you need to clear your browser cache!</p>\
            <p>* You can clear the browser cache by pressing <b>CTRL + SHIFT + R</b> a few times in a row on your keyboard.</p>\
            <div class="widgetButtonBox">\
                <button class="button _wide" type="button" onclick="startUpdate()">Continue</button>\
                <button class="button _wide" type="button" onclick="closeDs18b20Popup()">Don't Update</button>\
            </div></br>\
        </div>`);
}

function startUpdate() {  // popup indicating update is installing
    $('.ds18b20Popup-body').empty();
    ds18b20Popup.style.display = "block";
    document.querySelector("body").style.overflow = 'hidden';
    $('.ds18b20PopupHeader').empty();

    $(".ds18b20PopupHeader").append("Updating Robo-Tank");
    $(".ds18b20Popup-body").append(
        '<div style="text-align: center;">\
            <p>&nbsp;</p>\
            <p style="font-weight:bold">Updating to Robo-Tank version ' + latestVersion + '!</p>\
            <p style="font-weight:bold; color:#FF0000;">Important - After the installation completes you need to clear your browser cache!</p>\
            <p>* You can clear the browser cache by pressing <b>CTRL + SHIFT + R</b> a few times in a row on your keyboard.</p>\
            <p>During this process the controller will restart, you\'ll be notified when the update completes.</p>\
            <p>Keep this page open until the update is finished.</p>\
            <div class="updateRoller"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>\
            </br>Updating</br>\
        </div></br>');
    
    var command = "990";  // tell backend to start update
    sendToBackend(command);
}