
var tempOutletManual = 0;

function printAcOutletsWidget() {  // runs at firstRun
    // add sort box to header of AC outlet widget
    // document.getElementById('dashboardOutletContainer').innerHTML += 
    //     '<select name="sortOutlets" id="sortOutlets" class="sortHeaderBox" onchange="sortOutlets(value)">\
    //         <option value="1">Name</option>\
    //         <option value="2">Outlet Type</option>\
    //         <option value="3">GPIO Pin</option>\
    //     </select>\
    //     <div class="sortHeader">Sort</div>';

    // $('#sortOutlets').val(outletSortID);  // set sort select box to saved setting

    sortOutlets(outletSortID);
    // printAcOutlets();  // print outlets to widget
}

function printAcOutlets() {  // print outlets to dashboard
    $('#dashboardOutletContainer').empty();  // clear ac outlet widget
        
    // console.log('printAcOutlets---------------------------');
    // console.log(outletPinID.length);
    // console.log(outletGpioPinNumber);
    // console.log("displayScreen = " + displayScreen);
    if (displayScreen == 0) {
        document.getElementById('dashboardOutletContainer').innerHTML += 'AC Outlets</br>';
        for (var i = 0; i < outletPinID.length; i++) {

            if (outletAssigned[i] == 1)
            {
                // create divs for each outlet and fill with outlet icon and label
                document.getElementById('dashboardOutletContainer').innerHTML += `<div onclick="printAcOutletsManual()" class="dasboardOutletBox" id='outletPic_` + outletPinID[i] + `' title='` + outletName[i] + `'></div>`;
                
                // $('.dasboardOutletBox').tooltip();

                $( '.dasboardOutletBox' ).tooltip({
                    tooltipClass: "generalToolTip"
                });
                
                // print icon to screen
                document.getElementById('outletPic_' + outletPinID[i]).innerHTML = `<img id='outletIcon_` + outletPinID[i] + `' class='outletDashboard' src='images/Outlets/OutLD` + outletIconID[i] + `S.png'></div>`;
            }
        }
    }
}

function printAcOutletsManual() {  // print outlets to manual screen
    console.log('printAcOutletsManual---------------------------');
    // console.log(outletPinID.length);
    // console.log(outletGpioPinNumber);
    // console.log(outletPinID);
    printHeaderTitle("AC OUTLETS", "AC4.png");  // name and file

    removeFooter();
    // tempEmailEnabled[1] = email2Enabled[0];
    // tempEmailEnabled[2] = email3Enabled[0];

    document.getElementById('content').innerHTML =
        "<div class='cleanScreen' id='cleanScreen'>\
            <div class='settingsContainer' id='schOutletBox'></div>\
            <div class='widgetButtonBox'>\
                <button class='button _48 home_48' style='margin-top:10px;' type='button' onclick='loadLayout()'></button>\
            </div>\
        </div>";

    document.getElementById('schOutletBox').innerHTML += 
        `<div class="settingsTitle">Manually turn AC outlets On or Off.</div>`;


    for (var i = 0; i < outletPinID.length; i++) {
        if (outletAssigned[i] == 1) {
            outletUpdateIcon[i] = 1;
            // create divs for each outlet
            document.getElementById('schOutletBox').innerHTML += 
                `<div onclick="switchOutlet(` + outletPinID[i] + `)" class="manualOutletBox" id='outletPic_` + outletPinID[i] + `'></div>`;
                
            // print icon to screen
            document.getElementById('outletPic_' + outletPinID[i]).innerHTML = 
                `<img class='outletListBackgroundGrey' id='outletIcon_` + outletPinID[i] + `' src='images/Outlets/OutLD` + outletIconID[i] + `L.png'></br>` + outletName[i];
            
        }
    }

    document.getElementById('schOutletBox').innerHTML += 
        `<div class="settingsTitle"><span style="color:#FF0000;">Red Dot</span> = Manual Mode Enabled, nothing will switch AC Outlet</div>\
        <div class="outletsTitle">When you manually switch an AC outlet on or off it goes into Manual Mode and remains in this\
        state, even after a reboot, until you resume back to Auto Mode by clicking the red dot.</div>`;

    displayScreen = 2;
}

function outletResumeAuto(pinId) {  // switch AC outlets from widget    
    console.log('outletResumeAuto------- ' + pinId);
    for (var i=0; i < outletPinID.length; i++) {
        if (outletPinID[i] == pinId) {
            var command = "51," + pinId;
            sendToBackend(command);  // send pinID to backend for switching
            outletManual[i] = 0;
            outletUpdateIcon[i] = 1;
            document.getElementById('outletIconBox_' + outletPinID[i]).stopPropagation = true;
            autoUpdateOutletIcons();
            break;
        }
    }
}

function switchOutlet(pinId) {  // switch AC outlets from widget    

    var command = "50," + pinId;
    sendToBackend(command);  // send pinID to backend for switching

    tempOutletManual = 1;
    // console.log('switchOutlet------- ' + command);
}

function updateOutletStatus(id, value) {  // update outlet status as it comes in from backend
    // console.log("updateOutletStatus");
    for (var i=0; i < outletPinID.length; i++) {
        if (outletPinID[i] == id) {
            previousOutletStatus[i] = outletStatus[i];  // record previous state
            outletStatus[i] = value;  // record new state
            if (tempOutletManual == 1) {outletManual[i] = 1; tempOutletManual = 0;}
            // console.log('outletStatus[i] = ' + outletStatus[i]);
            if (previousOutletStatus[i] != outletStatus[i]) {outletUpdateIcon[i] = 1;}  // check if outlet state change, flag to update icon
            break;
        }
    }
}

function sortOutlets(sortID) {  // sort outlets
    // console.log('sortOutlets = ' + sortID);
    
    var sortType = "";  // clear sort type

    // get field name in table for sorting
    if (sortID == 1) {sortType = "name"}
    else if (sortID == 2) {sortType = "iconID"}
    else if (sortID == 3) {sortType = "gpio"}
    // console.log(sortType);

    outletSortID = sortID;  // track current sort type

    $.ajax({  // save sort type to database
        method: "POST",
        url: "/php/acOutletsSortSave.php",
        dataType: "text/plain",
        cache: false,
        data: {"v": sortID }
    });

    $.ajax({  // update all outlet variables so we have newly sorted data to work with
        method: "GET",
        url: "/php/acOutletsSort.php",
        cache: false,
        dataType: "json",
        data: {
            "s": sortType
        },
        success: function(dataWindow) {
            outletPinID = [];
            outletGpioPinNumber = [];
            outletName = [];
            outletAssigned = [];
            outletIconID = [];
            outletInvert = [];

            // console.log(dataWindow);
            for(var i in dataWindow) {
                outletPinID.push(dataWindow[i].pinID);
                outletGpioPinNumber.push(dataWindow[i].gpio);
                outletName.push(dataWindow[i].name);
                outletAssigned.push(dataWindow[i].assigned);
                outletIconID.push(dataWindow[i].iconID);
                outletInvert.push(dataWindow[i].invert);
                outletUpdateIcon[i] = 1;  // reset status flags so we can redraw icons
            }

            // var command = "51," + outletSortID;
            // sendToBackend(command);  // send new sort type to backend so it can update array order
            // console.log('sortOutlets------- ' + command);

            if (outletPinID.length > 0) {printAcOutlets();}
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - sortOutlets');
        }
    });
    
}

function autoUpdateOutletIcons(){  // update icons in widget if they have been flagged
    // console.log(outletGpioPinNumber);
    // console.log(outletUpdateIcon);
    // console.log(outletStatus);

    if ((displayScreen == 0) || (displayScreen == 2)) {
        // go through each outlet
        for(var i in outletPinID) {
            if (outletUpdateIcon[i] == 1)  // check if outlet status flag is set
            {
                outletUpdateIcon[i] = 0;  // update flag so we know icon was updated

                if (displayScreen == 0) {
                    document.getElementById('outletPic_' + outletPinID[i]).innerHTML =
                        `<div class="outletIconBox" id="outletIconBox_` + outletPinID[i] + `"><img id='outletIcon_` + outletPinID[i] + `' class='outletDashboard' src='images/Outlets/OutLD` + outletIconID[i] + `S.png'></div>`;  // load icon
                }
                else if (displayScreen == 2) {
                    document.getElementById('outletPic_' + outletPinID[i]).innerHTML = 
                        `<div class="outletIconBox" id="outletIconBox_` + outletPinID[i] + `"><img id='outletIcon_` + outletPinID[i] + `' class='outletListBackgroundGrey' src='images/Outlets/OutLD` + outletIconID[i] + `L.png'></br>` + outletName[i] + `</div>`;
                }
                // check state of outlet pin so we know color of icon to load
                if (outletStatus[i] == 1) {document.getElementById('outletIcon_' + outletPinID[i]).style.backgroundColor = "#00b610";}
                else {document.getElementById('outletIcon_' + outletPinID[i]).style.backgroundColor = "#444444";}

                if (outletManual[i] == 1) {  // manual mode is running, add red dot on outlet
                    if (displayScreen == 0) {  // dashboard
                        document.getElementById('outletIconBox_' + outletPinID[i]).innerHTML +=
                            '<div onclick="outletResumeAuto(' + outletPinID[i] + ')" id="outletIconManual_' + outletPinID[i] + '" class="outletDashManual">&#8226</div>';
                    }
                    if (displayScreen == 2) {  // manual outlet page
                        document.getElementById('outletIconBox_' + outletPinID[i]).innerHTML += 
                            '<div onclick="outletResumeAuto(' + outletPinID[i] + ')" id="outletIconManual_' + outletPinID[i] + '" class="outletIconManual">&#8226</div>';
                        
                        // stop icon onclick from running when the red dot is pressed on outlet
                        const iconBox = document.getElementById('outletIconManual_' + outletPinID[i]);            
                        iconBox.addEventListener("click", function (e) {
                            e.stopPropagation();
                        });
                    }
                }
                else {
                    if (displayScreen == 2) {document.getElementById('outletIconBox_' + outletPinID[i]).innerHTML += '';}  // Remove red dot on outlet
                }

            }
        }
    }
}