
var tempDCManual = 0;

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

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

    sortDcPorts(dcSortID);
    // printDcPorts();  // print DC ports to widget
}

function printDcPorts() {  // print DC ports to widget
    if (dcPinID.length > 0) {
        $('#dashboardDcContainer').empty();  // clear DC ports widget
            
        // console.log('printDcPorts---------------------------');
        // console.log(dcGpioPinNumber.length);
        // console.log(dcGpioPinNumber);
        // console.log(dcPinID);
        document.getElementById('dashboardDcContainer').innerHTML += 'DC Ports</br>';
        for (var i = 0; i < dcPinID.length; i++) {

            if (dcAssigned[i] == 1)
            {
                // create divs for each DC port and fill with DC port icon and label
                document.getElementById('dashboardDcContainer').innerHTML += `<div onclick="printDCManual()" class="dasboardDcBox" id='dcPic_` + dcPinID[i] + `' title='` + dcName[i] + `'></div>`;
                
                $( '.dasboardDcBox' ).tooltip({
                    tooltipClass: "generalToolTip"
                });

                // print icon to screen
                document.getElementById('dcPic_' + dcPinID[i]).innerHTML = `<img id='dcIcon_` + dcPinID[i] + `' class='outletDashboard' src='images/Outlets/OutLD` + dcIconID[i] + `S.png'></div>`;
            }
        }
    }
}

function printDCManual() {  // print DC ports to widget
    console.log('printDCManual---------------------------');
    // console.log(dcPinID.length);
    // console.log(dcPinID);
    printHeaderTitle("DC PORTS", "DC4.png");  // name and file

    removeFooter();

    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 DC ports On or Off.</div>`;


    for (var i = 0; i < dcPinID.length; i++) {
        if (dcAssigned[i] == 1) {
            dcUpdateIcon[i] = 1;
            // create divs for each DC port
            document.getElementById('schOutletBox').innerHTML += 
                `<div onclick="switchDcPort(` + dcPinID[i] + `)" class="manualOutletBox" id='dcPic_` + dcPinID[i] + `'></div>`;
                
            // print icon to screen
            document.getElementById('dcPic_' + dcPinID[i]).innerHTML = 
                `<img class='outletListBackgroundGrey' id='dcIcon_` + dcPinID[i] + `' src='images/Outlets/OutLD` + dcIconID[i] + `L.png'></br>` + dcName[i];
            
        }
    }
    
    document.getElementById('schOutletBox').innerHTML += 
        `<div class="settingsTitle"><span style="color:#FF0000;">Red Dot</span> = Manual Mode Enabled, nothing will switch DC Portt</div>\
        <div class="outletsTitle">When you manually switch a DC Port 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 = 3;
}

function dcResumeAuto(pinId) {  // switch AC outlets from widget    
    console.log('dcResumeAuto------- ' + pinId);
    for (var i=0; i < dcPinID.length; i++) {
        if (dcPinID[i] == pinId) {
            var command = "61," + pinId;
            sendToBackend(command);  // send pinID to backend for switching
            dcManual[i] = 0;
            dcUpdateIcon[i] = 1;
            document.getElementById('dcIconBox_' + dcPinID[i]).stopPropagation = true;
            autoUpdateDcIcons();
            break;
        }
    }
}

function switchDcPort(pinId) {  // switch DC ports from widget
    var command = "60," + pinId;
    sendToBackend(command);  // send pinID to backend for switching

    tempDCManual = 1;
    // console.log('switchDcPort------- ' + command);
}

function updateDcStatus(id, value) {  // update DC port status as data comes in from backend
    // console.log("updateDcStatus = " + id + ", " + value);
    for (var i=0; i < dcPinID.length; i++) {
        if (dcPinID[i] == id) {
            previousDcStatus[i] = dcStatus[i];  // record previous state
            dcStatus[i] = value;  // record new state
            if (tempDCManual == 1) {dcManual[i] = 1; tempDCManual = 0;}
            // console.log('dcStatus[i] = ' + dcStatus[i]);
            if (previousDcStatus[i] != dcStatus[i]) {dcUpdateIcon[i] = 1;}  // check if DC port state change, flag to update icon
            break;
        }
    }

    // var arrayID = 0;
    // var i = 0;
    // for(var i in dcPinID) {  // go through dc port status to see if icons need updating
    //     // console.log("dcPinID[i] = " + dcPinID[i]);
    //     if (dcPinID[i] == id) {arrayID = i; break;}
    //     i++;
    // }
    // previousDcStatus[arrayID] = dcStatus[arrayID];  // record previous state
    // dcStatus[arrayID] = value;  // record new state
    // // console.log('dcStatus[i] = ' + dcStatus[i]);
    // if (previousDcStatus[arrayID] != dcStatus[arrayID]) dcUpdateIcon[arrayID] = 1;  // check if dc port status change, flag to update icon
}

function sortDcPorts(sortID) {  // sort DC ports
    // console.log('sortDcPorts = ' + 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);

    dcSortID = sortID;  // track current sort type

    $.ajax({  // save sort type to database
        method: "POST",
        url: "/php/dcSortSave.php",
        dataType: "text/plain",
        cache: false,
        data: {"v": dcSortID }
        // success: function(dataWindow) {
        //     console.log('sortDcPorts Completed ------------------');
        //     console.log(dataWindow);
        // },
        // error: function(dataWindow) {
        //     console.log(dataWindow);
        //     console.log('sortDcPorts error');
        // }
    });

    $.ajax({  // update all dc port variables so we have newly sorted data to work with
        method: "GET",
        url: "/php/dcSort.php",
        // cache: false,
        dataType: "json",
        cache: false,
        data: {
            "s": sortType
        },
        success: function(dataWindow) {
            dcPinID = [];
            dcGpioPinNumber = [];
            dcName = [];
            dcAssigned = [];
            dcIconID = [];
            dcInvert = [];

            // console.log(dataWindow);
            for(var i in dataWindow) {
                // place list of DC ports in individual variables
                dcPinID.push(dataWindow[i].pinID);
                dcGpioPinNumber.push(dataWindow[i].gpio);
                dcName.push(dataWindow[i].name);
                dcAssigned.push(dataWindow[i].assigned);
                dcIconID.push(dataWindow[i].iconID);
                dcInvert.push(dataWindow[i].invert);
                dcUpdateIcon[i] = 1;  // reset status flags so we can redraw icons
            }

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

            printDcPorts();
        },
        error: function(dataWindow) {
            console.log(dataWindow);
            console.log('error - sortDcPorts');
        }
    });
    
}

function autoUpdateDcIcons(){  // update icons in widget if they have been flagged
    // console.log(outletGpioPinNumber);
    // console.log(dcUpdateIcon);
    // console.log(dcStatus);

    if ((displayScreen == 0) || (displayScreen == 3)) {
        // go through each DC port
        for(var i in dcPinID) {
            if (dcUpdateIcon[i] == 1)  // check if DC port status flag is set
            {
                dcUpdateIcon[i] = 0;  // update flag so we know icon was updated

                if (displayScreen == 0) {
                    document.getElementById('dcPic_' + dcPinID[i]).innerHTML =
                        `<div class="outletIconBox" id="dcIconBox_` + dcPinID[i] + `"><img id='dcIcon_` + dcPinID[i] + `' class='outletDashboard' src='images/Outlets/OutLD` + dcIconID[i] + `S.png'></div>`;  // load icon
                }
                else if (displayScreen == 3) {
                    document.getElementById('dcPic_' + dcPinID[i]).innerHTML = 
                        `<div class="outletIconBox" id="dcIconBox_` + dcPinID[i] + `"><img id='dcIcon_` + dcPinID[i] + `' class='outletListBackgroundGrey' src='images/Outlets/OutLD` + dcIconID[i] + `L.png'></br>` + dcName[i] + `</div>`;
                }
                // check state of DC port pin so we know color of icon to load
                if (dcStatus[i] == 1) {document.getElementById('dcIcon_' + dcPinID[i]).style.backgroundColor = "#00b610";}
                else {document.getElementById('dcIcon_' + dcPinID[i]).style.backgroundColor = "#444444";}

                if (dcManual[i] == 1) {  // manual mode is running, add red dot on DC port
                    if (displayScreen == 0) {  // dashboard
                        document.getElementById('dcIconBox_' + dcPinID[i]).innerHTML +=
                            '<div onclick="dcResumeAuto(' + dcPinID[i] + ')" id="dcIconManual_' + dcPinID[i] + '" class="outletDashManual">&#8226</div>';
                    }
                    if (displayScreen == 3) {  // manual DC port page
                        document.getElementById('dcIconBox_' + dcPinID[i]).innerHTML += 
                            '<div onclick="dcResumeAuto(' + dcPinID[i] + ')" id="dcIconManual_' + dcPinID[i] + '" class="outletIconManual">&#8226</div>';
                        
                        // stop icon onclick from running when the red dot is pressed on DC port
                        const iconBox = document.getElementById('dcIconManual_' + dcPinID[i]);            
                        iconBox.addEventListener("click", function (e) {
                            e.stopPropagation();
                        });
                    }
                }
                else {
                    if (displayScreen == 3) {document.getElementById('dcIconBox_' + dcPinID[i]).innerHTML += '';}  // Remove red dot on DC port
                }

            }
        }
    }
}
