// add lines below to /boot/config.txt to enable extra 1-wire buses
// dtoverlay=w1-gpio,gpiopin=4
// dtoverlay=w1-gpio,gpiopin=17

var newDs18b20Address = "";  // used to store new sensor address while assigning custom name
var ds18b20Popup = document.getElementById("ds18b20Popup");  // define DS18B20 popup for min/max and custom name

function DS18B20incoming(id, temp, humidity, min, max){  // continually update sensor data coming from backend
    // console.log('updateDS18B2 = ' + id + ", " + temp + ", " + humidity + ", " + min + ", " + max);
    // console.log('ds18b20AddrFound[i]   = ' + ds18b20AddrFound);
    for(var i in ds18b20AddrFound) {  // 
        if ((ds18b20AddrFound[i] == id) && (temp != 999999)) {  // check ID's match and sensor isn't missing
            ds18b20Temp[i] = temp;  // clear temps
            ds18b20Humidity[i] = humidity;  // clear temps
            ds18b20Min[i] = min;  // clear min
            ds18b20Max[i] = max;  // clear max
            break;
        }
        i++;
    }
}

function update_ds18b20() {  // continually update sensor data from database
    // console.log('update_ds18b20&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&');

    // update time on website
    printDateTime();

    $.ajax({  // get ds18b20 sensor names
        url: "/php/ds18b20Read.php",
        method: "GET",
        cache: false,
        success: function(dataWindow) 
        {
            previousDs18b20Found = ds18b20Found;   // store number of sensors found before reading sensor data so we know if one was plugged in
            var ds18b20Plugged = [];  // clear ds18b20Plugged
            ds18b20Name = [];  // all custom names in database
            ds18b20AddrSaved = [];  // all ds18b20 internal IDs in database
            ds18b20AddrFound = [];  // ds18b20 internal ID of sensors plugged in
            ds18b20NamePlugged = [];  // custom names of sensors plugged in
            ds18b20Found = 0;  // reset how many ds18b20 sensors are seen
            ds18b20Saved = 0;  // tracks how many sensors are in database

            for(var i in dataWindow) 
            {
                // get data for all sensors in database
                ds18b20Plugged.push(dataWindow[i].plugged);  // tracks if sensor is plugged in or not
                ds18b20Name.push(dataWindow[i].name);  // custom name
                ds18b20AddrSaved.push(dataWindow[i].address);  // ds18b20 internal ID

                if (ds18b20Plugged[i] == 1)  // get send data only for plugged in sensors
                {
                    ds18b20AddrFound.push(dataWindow[i].address);  // ds18b20 internal ID
                    ds18b20NamePlugged.push(dataWindow[i].name);  // custom names
                    ds18b20Found++;  // tracks how many sensors are plugged in
                }
                ds18b20Saved++;  // tracks how many sensors are in database
            }
            
            if ((startupWizardRunning == 0) && (previousDs18b20Found != ds18b20Found)) {redrawTempWidget = 1;}  // check if state change and flag for outlet icon

            if (displayScreen == 0) {printTemps();}
        },
        error: function(dataWindow) {
            // console.log('ERROR - reading database ds18b20 -----------------------------------------------------------------');
            // console.log(dataWindow);// no sensor data
        }
    });
}

function printTemps() {  // print temps and redraw gauges in widget
    // var command = "998";
    // incomingBackend(command);  // send slider value to backend

    redrawDashboardCol1();
    var i = 0;
    // go though each ds18b20 sensor and print to widget
    while (i < ds18b20Found) 
    {
        if (redrawTempWidget == 1) {checkDs18b20Name();}  // sensor count changed, check if they all have custom names
        // check if we have a temperature reading
        if ((ds18b20Temp[i] != 0) && (redrawTempWidget != 2))  // pause printing temp gauges in widget while assigning custom name
        {
            // console.log("reload");
            
            if (redrawTempWidget == 3)  // redraw the temperature gauges in widget once after assigning custom name
            {
                // redrawDashboardCol1();
                // console.log('redrawTempWidget----------------------');
                // print temp gauges to widget
                document.getElementById('dashboardDataBox_' + i).innerHTML += 
                    '<div class="dashboardTemp" id="dashboardTemp_' + i + '">\
                        <div class="thermoIcon">\
                            <img class="" src="images/icons/temp.png">\
                        </div>\
                        <div class="thermoBox">\
                            <div class="thermoName" id="thermoName' + [i] + '"></div>\
                            <div class="thermoTemp" id="thermoTemp' + [i] + '">\</div>\
                            <div class="thermoMinLabel" id="thermoMinLabel">Min</div>\
                            <div class="thermoMaxLabel" id="thermoMaxLabel">Max</div>\
                            <div class="thermoMin" onclick="openDs18b20MinMaxPopup(' + i + ',0)" id="thermoMin' + [i] + '"></div>\
                            <div class="thermoMax" onclick="openDs18b20MinMaxPopup(' + i + ',1)" id="thermoMax' + [i] + '"></div>\
                        </div>\
                    </div>';
            }
            
            document.getElementById('thermoTemp' + [i]).innerHTML = Math.round(ds18b20Temp[i] * 100) / 100 + '\u00B0';  // update temperature text
            if (ds18b20Humidity[i] != 0) {
                document.getElementById('thermoTemp' + [i]).innerHTML += 
                    '<div class="thermoHumidity" id="thermoHumidity' + [i] + '">\
                        ' + Math.round(ds18b20Humidity[i] * 100) / 100 + '\u0025' + '\
                    </div>';  // update temperature text
            }
            else {document.getElementById('thermoTemp' + [i]).innerHTML += "";}
            document.getElementById('thermoName' + [i]).innerHTML = ds18b20NamePlugged[i];  // update custom name
            document.getElementById('thermoMax' + [i]).innerHTML = Math.round(ds18b20Max[i] * 10) / 10 + '\u00B0';  // update max temp
            document.getElementById('thermoMin' + [i]).innerHTML = Math.round(ds18b20Min[i] * 10) / 10 + '\u00B0';  // update min temp

            // rescale widget guages once after all have been draw
            if ((i == ds18b20Found-1) && (redrawTempWidget == 3)) {redrawTempWidget = 0;}// console.log('redrawTempWidget Finished----------------------');}  // all temp guages have been drawn to widget
        }
        i++;  // go to next ds18b20
    }
    if (redrawTempWidget == 1)  // empty widget when no sensors are found
    {
        console.log('redrawTempWidget Empty----------------------');
        redrawTempWidget = 0;
    }

}

function checkDs18b20Name() {  // check if ds18b20 sensors have a custom name, add if necessary
    // console.log('checkDs18b20Name-------------');
    // console.log('ds18b20Found = ' + ds18b20Found);
    redrawTempWidget = 2;  // stop guages in widget from redrawing while adding custom name
    for (var i=0; i < ds18b20Found; i++)
    {
        // console.log('ds18b20NamePlugged[i] = ' + ds18b20NamePlugged[i]);
        if (ds18b20NamePlugged[i] == null)  // check if sensor has a custom name 
        {
            var text = "";
            if (ds18b20AddrFound[i].startsWith("dht")) {text = "DHT22 temperature and humidity sensor";}
            else {text = "DS18B20 temperature sensor";}

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

            $('.ds18b20PopupHeader').empty();
            $(".ds18b20PopupHeader").append("New DS18B20 Temperature Sensor Detected");
            
            $(".ds18b20Popup-body").append(
                '<p>&nbsp;</p>\
                <p style="text-align: center;">Robo-Tank has detected a new ' + text + ', please add a custom name below for your reference.</p>\
                <p></p>\
                <p style="text-align: center;">Sensor ID = ' + ds18b20AddrFound[i] + '</p>\
                <p></p>\
                <form style="text-align: center;">\
                    <label class="settingsLabels" for="ds18name">DS18B20 Custom Name:</label>\
                    <input class="settingsFields" type="text" id="ds18name" name="ds18name"><br>\
                </form>\
                <div id="popupErrorMessage"></div><br>\
                <div class="widgetButtonBox">\
                    <button class="button _wide" type="button" onclick="ds18b20SaveName()">Save</button>\
                </div></br>');
                // <center><input class="button" type="button" value="Save" onclick="ds18b20SaveName()" /></center><br>');

            newDs18b20Address = ds18b20AddrFound[i];  // store array location so we can use when name is saved
            console.log('WAITING FOR NAME GIVEN ----------------------------------------');
            return;
        }
    }
    redrawTempWidget = 3;  // mark name check complete so we can redraw widget on dashboard
    // console.log('FINISHED checkDs18b20Name ----------------------------------------');
    if (startupWizardRunning == 1) {startupSetupComplete();}  // last step of first run setup wizard, only used for setup scan
}

function ds18b20SaveName() {  // save custom name to database
    var name = document.getElementById("ds18name").value;  // get custom name entered in form
    console.log('ds18b20SaveName PRESSED --------------------------------------------------------------');
    console.log(name);
    console.log(newDs18b20Address);
    if (name == "")  // check if custom name was entered, if not warn user.
    {
        document.getElementById('popupErrorMessage').innerHTML = "Please enter a custom name to continue!";
    }
    else  // all good save and close popup
    {
        var command = "14," + newDs18b20Address + "," + name;
        sendToBackend(command);  // send slider value to backend
        console.log('command = ' + command);
    
        if (startupWizardRunning == 1) {  // check temp sensors during first run setup wizard, only used for setup scan
            $('.ds18b20Popup-body').empty();
            $(".ds18b20Popup-body").append(
                '<p>&nbsp;</p>\
                <p>&nbsp;</p>\
                <p>&nbsp;</p>\
                <p class="h1" style="text-align: center;">Scanning for more sensors...</p>\
                <p>&nbsp;</p>\
                <p>&nbsp;</p>\
                <p>&nbsp;</p>');

            setTimeout(update_ds18b20, 500);
        }
        else {ds18b20Popup.style.display = "none"; document.querySelector("body").style.overflow = 'visible';}  // hide popup
        $('#popupBackground').hide();  // hide greyed out background
        setTimeout(checkDs18b20Name, 1000);  // wait 1 second before checking if more custom names are needed
        // setTimeout(printDs18b20Graphs, 300000);  // wait 1 second before drawing graphs so we see new custom names
    }
}

function loadLiveGraph(id) {  // currently not being used
    // console.log('loadLiveGraph........................................');
    var data = [];
    var s = ds18b20Temp[0] - 0.01;
    var t = new Date();
    for (var i = 10; i >= 0; i--) {
        var x = new Date(t.getTime() - i * 1000);
        var y = ds18b20Temp[0];
        // console.log(y);
        data.push([t, s]);
    }

    var g = new Dygraph(
        document.getElementById("ds18b20GraphDiv" + id), data,
        {
            drawPoints: true,
            showRoller: true,
            rollPeriod: 10,
            // valueRange: [0.0, 1.2],
            labels: ['Date', 'Temp']
        });

    // store state in window.
    window.intervalId = setInterval(function() {
        var x = new Date();  // current time
        var y = ds18b20Temp[0];
        // console.log(ds18b20Temp[0]);
        // console.log(y);
        data.push([x, y]);
        g.updateOptions( { 'file': data } );
    }, 1000);
}

function resetDs18b20Min(i) {  // reset min temp
    var command = "12," + ds18b20AddrFound[i];
    sendToBackend(command);  // send slider value to backend

    console.log('resetDs18b20Min -- ' + ds18b20AddrFound[i]);
    closeDs18b20Popup();
}

function resetDs18b20Max(i) {  // reset max temp
    var command = "13," + ds18b20AddrFound[i];
    sendToBackend(command);  // send slider value to backend
    console.log('resetDs18b20Max -- ' + ds18b20AddrFound[i]);
    
    closeDs18b20Popup();
}

function openDs18b20MinMaxPopup(i, l) {  // open dialog box to confirm min or max reset
    // console.log('openDs18b20MinMaxPopup');
    // console.log(i);
    // console.log(l);
    $('#popupBackground').show();  // grey out background
    $('.ds18b20Popup-body').empty();
    ds18b20Popup.style.display = "block";
    document.querySelector("body").style.overflow = 'hidden';
    $('.ds18b20PopupHeader').empty();
    if (l == 0) {
        $(".ds18b20PopupHeader").append("Reset DS18B20 Minimum Temperature");
        $(".ds18b20Popup-body").append(
            '<div style="text-align: center;">\
                <p>&nbsp;</p>\
                <p>Are you sure you want to reset the minimum recorded temperature for ' + ds18b20NamePlugged[i] + '?</p>\
                <div class="widgetButtonBox">\
                    <button class="button _wide" type="button" onclick="resetDs18b20Min(`' + i + '`)">Yes</button>\
                    <button class="button _wide" type="button" onclick="closeDs18b20Popup()">No</button>\
                </div></br>\
            </div>');
    }
    else {
        $(".ds18b20PopupHeader").append("Reset DS18B20 Maximum Temperature");
        $(".ds18b20Popup-body").append(
            '<div style="text-align: center;">\
                <p>&nbsp;</p>\
                <p>Are you sure you want to reset the maximum recorded temperature for ' + ds18b20NamePlugged[i] + '?</p>\
                <div class="widgetButtonBox">\
                    <button class="button _wide" type="button" onclick="resetDs18b20Max(`' + i + '`)">Yes</button>\
                    <button class="button _wide" type="button" onclick="closeDs18b20Popup()">No</button>\
                </div></br>\
            </div>');
    }
}

function closeDs18b20Popup() {  // close ds18b20 dialog box
    // console.log('closeDs18b20Popup ------------------------------=====================');
    ds18b20Popup.style.display = "none";  // hide popup
    document.querySelector("body").style.overflow = 'visible';
    $('.ds18b20Popup-body').empty();
    $('#popupBackground').hide();  // hide greyed out background
}

