
var lightModeSlider = [];
var editingPinID = 0;

function updateNextLightDashboard() {  //
    var dt = new Date();
    var secs = dt.getSeconds() + (60 * (dt.getMinutes() + (60 * dt.getHours())));

    // if (displayScreen == 0) {
    //     for (var i=0; i < lightModeID.length; i++) {  // get current schedule number
    //         if (lightCurrentScheduleID == lightModeID[i]) {
    //             document.getElementById('lightModeName').innerHTML = lightModeName[i]; break;
    //         }
    //     }

    //     for (var i=0; i < lightModeID.length; i++) {  // get next schedule number
    //         if (lightNextScheduleID == lightModeID[i]) {
    //             // console.log('lightModeStart             = ' + lightModeStart[i]);
    //             document.getElementById('lightModeLabel').innerHTML = lightModeName[i];
    //             document.getElementById('lightModeNext').innerHTML = secondsToTime(lightModeStart[i] - secs); break;
    //         }
    //     }
    // }
}

function printLightWidget() {  // runs from firstRun.js

    // console.log('printLightWidget-----------');

    document.getElementById('contentCol2_Col1').innerHTML += 
    '<div class="dashboardLightMode" id="dashboardLightMode">\
        <div class="lightModeName" id="lightModeName"></div>\
        <div class="lightModeBox">\
            <div class="lightModeIcon">\
                <img class="" src="images/icons/moon/moon14.png">\
            </div>\
            <div class="lightModeInfo">\
                <div class="lightModeLabel" id="lightModeLabel"></div>\
                <div class="lightModeLabel">starting in</div>\
                <div class="lightModeLabel" id="lightModeNext">is coming in</div>\
            </div>\
        </div>\
    </div>';

    updateNextLightDashboard(); 
}

function viewLightModes()  // print sliders to screen
{
    // console.log(lightModeStart);
    // console.log('printSliders------ ');
    
    printHeaderTitle("LIGHT MODES", "lights_sm.png");  // name and file
    removeFooter();
    
    document.getElementById('content').innerHTML +=
        "<div class='cleanScreen'>\
                <div class='lightsWidgetBoxContainer' id='lightsWidgetBoxContainer'></div>\
        </div>";

    $('.lightsWidgetBoxContainer').empty();

    document.getElementById('lightsWidgetBoxContainer').innerHTML += 
        '<div class="widgetButtonBox" style="margin-top:-15px;">\
            <button class="button _wide" style="margin-top:20px;" type="button" onclick="newLightMode()">Add New Mode</button>\
        </div>';

    // print section for each light port being used
    for (var c = 0; c < pinTypeID.length; c++)  // go through each pin
    {
        for (var i = 0; i < lightModePinID.length; i++)  // go through each light mode
        {
            if (lightModePinID[i] == portsPinID[c]) {  // check if there's a light mode matching the pin being looked at
                document.getElementById('lightsWidgetBoxContainer').innerHTML +=  // draw light port section
                    '<div class="modeDetailsBox">\
                            <div class="lightModePortName" id="portName_' + portsPinID[c] + '" onclick="expandLightMode(' + lightModePinID[i] + ')">\
                                ' + customPortName[c] + '\
                                <div class="lightModeEnable bi bi-toggle-on" id="lightModeEnable_' + lightModePinID[i] + '" onclick="lightModeEnable(' + lightModePinID[i] + ')"></div>\
                                <div class="lightModeAddMode bi bi-plus-lg" id="portAddMode_' + portsPinID[c] + '" onclick="addLightMode(' + lightModePinID[i] + ')"> Add Mode</div>\
                            </div>\
                            <div class="lightModePortModesBox" id="portSettings_' + portsPinID[c] + '">\
                            <div class="lightModePortModesBox2" id="lightModePortModesBox_' + lightModePinID[i] + '"></div>\
                            </div>\
                    </div>';
                break;  // only need one so go to next pin
            }
        }
    }

    var sliderArray = 0;
    // print modes for each light port
    for (var c = 0; c < pinTypeID.length; c++)  // go through each pin
    {
        for (var i = 0; i < lightModePinID.length; i++)  // go through each light mode
        {
            if (lightModePinID[i] == portsPinID[c]) {  // check if there's a light mode matching the pin being looked at
                document.getElementById('portSettings_' + portsPinID[c]).innerHTML +=  // draw slider and details for each mode
                    '<div class="lightModePortDetailsBox">\
                        <input class="lightModeStart" type="time" step="1" id="modeTime_' + i + '" onfocusout="lightModeSaveTime(' + i + ')" value="' + secondsToTime(lightModeStart[i]) + '" autocomplete="off">\
                        <div class="lightModePortDetails">\
                            <div class="sliderBox">\
                                <input type="range" min="0" max="4095" oninput="moveSlider(' + i + ',' + sliderArray + ',' + lightModeID[i] + ')" onmouseup="stopSlider(' + i + ',' + sliderArray + ',' + lightModeID[i] + ')" value="' + lightModeStartLevel[i] + '" class="lightSlider" id="lightSlider_' + sliderArray + '">\
                            </div>\
                            <div class="lightModeLevelLabel">Level</div>\
                            <input class="lightModeLevel" type="text" id="chValue_' + sliderArray + '" onchange="editSliderValue(' + i + ',' + sliderArray + ',' + lightModeID[i] + ')" onfocusout="" value="" autocomplete="off">\
                            <img src="images/icons/lightOff.png" class="lightModeIcons" style="padding-left:3px; padding-bottom:6px; width: 24px; height: auto;" id="lightModeOn_' + sliderArray + '" onclick="">\
                            <div class="lightModeIcons bi bi-trash" id="lightModeDelete_' + sliderArray + '" onclick="lightModeDelete(' + lightModePinID[i] + ',' + lightModeID[i] + ')"></div>\
                        </div>\
                    </div>';
                sliderArray++;
            }
        }
    }
    
    document.getElementById('lightsWidgetBoxContainer').innerHTML += 
        '<div class="modesPortsAvailable" id="portsAvailable">Click an Available Light Port to Add Modes</br></div>\
        <div class="widgetButtonBox" style="margin-top:-15px;">\
            <button class="button _48 home_48" style="margin-top:20px;" type="button" onclick="loadLayout()"></button>\
        </div>';

    // print buttons for each light port not being used
    for (var c = 0; c < pinTypeID.length; c++)  // go through each pin
    {
        if ((pinTypeID[c] == 11) && (pinAssigned[c] == 1))  // find pins assigned as a light and enabled
        {
            var div = document.getElementById('portName_' + portsPinID[c]);  // check if pin already has a light mode
            if (div == null) {  // if div exists go on
                document.getElementById('portsAvailable').innerHTML += 
                    '<div class="modesPortBox" id="portsAvailable_' + portsPinID[c] + '" onclick="addLightPort(' + portsPinID[c] + ')">' + customPortName[c] + '</div>';
            }
        }
    }

    sliderArray = 0;
    // activate sliders
    for (var c = 0; c < pinTypeID.length; c++)  // go through each pin
    {
        for (var i = 0; i < lightModePinID.length; i++)  // go through each light mode
        {
            if (lightModePinID[i] == portsPinID[c]) {  // check if there's a light mode matching the pin being looked at

                lightModeSlider[sliderArray] = document.getElementById("lightSlider_" + sliderArray);
                // console.log("lightModeSlider = " + lightModeSlider[sliderArray].value);
                // console.log("chValue_" + sliderArray);
                document.getElementById("chValue_" + sliderArray).value = lightModeSlider[sliderArray].value;

                if (lightModeEnabled[i] == 0) {
                    document.getElementById("lightModeEnable_" + lightModePinID[i]).style.color = "#FF0000";
                    document.getElementById("lightModeEnable_" + lightModePinID[i]).className = 'lightModeEnable bi bi-toggle-off';
                    document.getElementById("lightModePortModesBox_" + lightModePinID[i]).style.display = "block";
                    document.getElementById('portAddMode_' + lightModePinID[i]).style.display = "none";  // hide add mode button when collapsed
                }
                else {
                    document.getElementById("lightModeEnable_" + lightModePinID[i]).style.color = "#00b610";
                    document.getElementById("lightModeEnable_" + lightModePinID[i]).className = 'lightModeEnable bi bi-toggle-on';
                }

                sliderArray++;
            }
        }
    }
    expandLightMode(editingPinID);
}

function lightModeSaveTime(arrayID){  // save light mode time
    // console.log("lightModeSaveTime = " + document.getElementById("modeTime_" + arrayID).value);
    // console.log("lightModeSaveTime = " + secondsFromTime(document.getElementById("modeTime_" + arrayID).value));

    lightModeStart[arrayID] = secondsFromTime(document.getElementById("modeTime_" + arrayID).value);
    editingPinID = lightModePinID[arrayID];  // temporarily store pinID so we can expand after reading back modes
    
    var command = "11, " + lightModeID[arrayID] + "," + secondsFromTime(document.getElementById("modeTime_" + arrayID).value);
    sendToBackend(command);  // send to backend
}

function editSliderValue(arrayID, sliderArray, modeID){  // update slider when text box is used
    if (document.getElementById("chValue_" + sliderArray).value == "") {  // text box empty
        lightModeSlider[sliderArray].value = 0;
        lightModeStartLevel[arrayID] = 0;
        document.getElementById("chValue_" + sliderArray).value = 0;
    }
    else if (document.getElementById("chValue_" + sliderArray).value > 4095) {
        lightModeSlider[sliderArray].value = 4095;
        lightModeStartLevel[arrayID] = 4095;
        document.getElementById("chValue_" + sliderArray).value = 4095;
    }
    else if (document.getElementById("chValue_" + sliderArray).value < 0) {
        lightModeSlider[sliderArray].value = 0;
        lightModeStartLevel[arrayID] = 0;
        document.getElementById("chValue_" + sliderArray).value = 0;
    }
    else {
        lightModeSlider[sliderArray].value = document.getElementById("chValue_" + sliderArray).value;
        lightModeStartLevel[arrayID] = document.getElementById("chValue_" + sliderArray).value;
    }

    var command = "2," + modeID + "," + document.getElementById("chValue_" + sliderArray).value;
    sendToBackend(command);  // send slider value to backend
}

function moveSlider(arrayID, sliderArray, modeID){  // update slider when moved and send value to backend
    document.getElementById("chValue_" + sliderArray).value = lightModeSlider[sliderArray].value;
    lightModeStartLevel[arrayID] = lightModeSlider[sliderArray].value;
    stopSendingData = 100;  // pause communcations
    var command = "1," + modeID + "," + lightModeSlider[sliderArray].value;
    sendToBackend(command);  // send slider value to backend
}

function stopSlider(arrayID, sliderArray, modeID){  // when slider is released make sure last value is sent to backend
    // console.log("FINISHED = " + lightModeSlider[sliderArray].value);
    // console.log("modeID = " + modeID);
    stopSendingData = 0;  // resume communcations
    
    document.getElementById("chValue_" + sliderArray).value = lightModeSlider[sliderArray].value;
    lightModeStartLevel[arrayID] = lightModeSlider[sliderArray].value;
    
    var command = "2," + modeID + "," + lightModeSlider[sliderArray].value;
    sendToBackend(command);  // send slider value to backend
}

function lightModeEnable(pinID){  // enable/disable light mode
    // console.log("sliderArray = " + sliderArray);
    expandLightMode(pinID);  // re-expand light mode as it'll collapse when button is pressed
    var enabled = 0;
    for (var c = 0; c < lightModePinID.length; c++)  // go through each pin
    {
        if (lightModePinID[c] == pinID) {
            if (lightModeEnabled[c] == 0) {
                lightModeEnabled[c] = 1;
                enabled = 1;
                document.getElementById("portAddMode_" + lightModePinID[c]).style.display = "none";  // hide add mode button when collapsed
                document.getElementById("lightModeEnable_" + lightModePinID[c]).style.color = "#00b610";
                document.getElementById("lightModeEnable_" + lightModePinID[c]).className = 'lightModeEnable bi bi-toggle-on';
                document.getElementById("lightModePortModesBox_" + lightModePinID[c]).style.display = "none";
            }
            else {
                lightModeEnabled[c] = 0;
                enabled = 0;
                document.getElementById("portAddMode_" + lightModePinID[c]).style.display = "none";  // hide add mode button when collapsed
                document.getElementById("lightModeEnable_" + lightModePinID[c]).style.color = "#FF0000";
                document.getElementById("lightModeEnable_" + lightModePinID[c]).className = 'lightModeEnable bi bi-toggle-off';
                document.getElementById("lightModePortModesBox_" + lightModePinID[c]).style.display = "block";
            }
        }
    }
    // console.log("lightModeEnabled = " + lightModeEnabled);
    var command = "10," + pinID + "," + enabled;
    sendToBackend(command);  // send to backend
}

function newLightMode(){  // add new light mode
    // console.log("newLightMode = " + pinID);
    
    $('.lightsWidgetBoxContainer').empty();

    document.getElementById('lightsWidgetBoxContainer').innerHTML += 
        '<div class="widgetButtonBox" style="margin-top:-15px;">\
            <button class="button _wide" style="margin-top:20px;" type="button" onclick="newLightMode()">Add New Mode</button>\
        </div>';
        
    document.getElementById('lightsWidgetBoxContainer').innerHTML += 
        '<div class="modesPortsAvailable" id="portsAvailable">Click an Available Light Port to Add Modes</br></div>\
        <div class="widgetButtonBox" style="margin-top:-15px;">\
            <button class="button _48 home_48" style="margin-top:20px;" type="button" onclick="loadLayout()"></button>\
        </div>';
    // editingPinID = pinID;  // temporarily store pinID so we can expand after reading back modes
    // expandLightMode(pinID);  // re-expand light mode as it'll collapse when button is pressed
    // var command = "7, " + pinID;
    // sendToBackend(command);  // send to backend
}

function addLightMode(pinID){  // add extra light mode for specific pinID
    // console.log("addLightMode = " + pinID);
    editingPinID = pinID;  // temporarily store pinID so we can expand after reading back modes
    expandLightMode(pinID);  // re-expand light mode as it'll collapse when button is pressed
    var command = "7, " + pinID;
    sendToBackend(command);  // send to backend
}

function addLightPort(pinID){  // add first light mode for specific pinID
    // console.log("addLightPort = " + pinID);
    editingPinID = pinID;  // temporarily store pinID so we can expand after reading back modes
    var command = "7, " + pinID;
    sendToBackend(command);  // send to backend
}

function lightModeDelete(pinID, modeID){  // delete light mode
    // console.log("lightModeDelete = " + modeID);
    editingPinID = pinID;  // temporarily store pinID so we can expand after reading back modes
    var command = "6, " + modeID;
    sendToBackend(command);  // send to backend
}

function expandLightMode(pinID) {  // expand light mode on list and show sliders
    // show or hide light mode content block
    // console.log('expandLightMode------');
    // console.log(modeN);
    
    var divExists = document.getElementById('portSettings_' + pinID);  // check if div is drawn
    if(divExists) {
        slidersDrawn = [];  // empty array that tracks sliders as they need to be redrawn after sorting modes
        if (document.getElementById('portSettings_' + pinID).style.display === "inline-block") {  // collapse content
            document.getElementById('portSettings_' + pinID).style.marginBottom = "0px";  // remove bottom margin
            document.getElementById('portSettings_' + pinID).style.display = "none";  // collapse content
            document.getElementById('portAddMode_' + pinID).style.display = "none";  // hide add mode button when collapsed
            document.getElementById('portName_' + pinID).style.borderBottomLeftRadius = "15px";
            document.getElementById('portName_' + pinID).style.borderBottomRightRadius = "15px";
        }
        else {  // expand content
            document.getElementById('portSettings_' + pinID).style.display = "inline-block";  // expand content

            for (var c = 0; c < lightModePinID.length; c++)  // go through each pin
            {
                if ((lightModePinID[c] == pinID) && (lightModeEnabled[c] == 1)) {
                    document.getElementById('portAddMode_' + pinID).style.display = "block";  // show add mode button when expanded
                    break;
                }
            }
            document.getElementById('portName_' + pinID).style.borderBottomLeftRadius = "0px";
            document.getElementById('portName_' + pinID).style.borderBottomRightRadius = "0px";
        }
        // for (var i=0; i < lightModeNumber.length; i++)  // close sliders being viewed for new for selection
        // {
        //     if (i != modeN) {
        //         document.getElementById('lightModeList' + i).style.backgroundColor = "rgb(255, 255, 255)";  // change row background to white
        //         document.getElementById('lightModeList' + i).style.color = "rgb(0, 0, 0)";  // change text color to black
        //         document.getElementById('portSettings_' + i).style.marginBottom = "0px";  // remove bottom margin
        //         document.getElementById('portSettings_' + i).style.display = "none";  // collapse content
        //         document.getElementById('expandIcon_' + i).innerHTML =  // change collapse icon
        //             '<div class="lightModesListIcon bi bi-arrow-90deg-down" style="margin-left:8px; font-size:11px"></div>'
        //     }
        // }
    }
}

function updateLightModes(){  // this is run from firstRun after backend response with go ahead
    // console.log("updateLightModes --------------");
    updatingUI = 1;
    getLightModes();
}