require("luamods/command")
require("luamods/layout")
require("luamods/cgi")
require("config/rsm_conf")

header = layout.getHeader()
footer = layout.getFooter()

userLevel = db.getPriv(layout.username) or 1

if (userLevel == 1) then
    buttonControl = " disabled"
    inputControl = " readonly"
else
    buttonControl = ""
    inputControl = ""
end

stateStrings = {}
stateStrings["00"] = "DISCOVERED"
stateStrings["01"] = "MAINTENANCE"
stateStrings["02"] = "OPERATIONAL"
stateStrings["03"] = "UNKNOWN"

statusStrings = {}
statusStrings["00"] = "OFFLINE"
statusStrings["01"] = "ONLINE"
statusStrings["02"] = "UNKNOWN"

typeStrings = {}
typeStrings["00"] = "IO"
typeStrings["01"] = "AC"
typeStrings["02"] = "ANALOG"
typeStrings["03"] = "ANALOG_IO"
typeStrings["04"] = "SNMP"
typeStrings["05"] = "MODBUS"
typeStrings["06"] = "DLMS"
typeStrings["07"] = "OTHER"
typeStrings["08"] = "UNKNOWN"

devID = cgi.get.devID or cgi.post.devID
if (devID == nil) or (devID == "") then devID = "unknown" end

section = cgi.get.section or ""
if (section ~= "ports") and (section ~= "inputs") and (section ~= "outputs") and (section ~= "analog") and (section ~= "analogout") then section = "config" end

siteConfig = command.ex(rsm_conf.rsmc_path..[[ GET: TAG_SITE_CFG]]) or ""
siteLabel = siteConfig:match([[TAG_SITE_LABEL=%"([^%"]+)%"]]) or "unknown"
devConfig = command.ex(rsm_conf.rsmc_path..[[ GET: TAG_DEV_CFG TAG_DEV_ID=]]..devID) or ""

if (devConfig:match("TAG_DEV_ID=(%x+)") ~= devID) then devConfig = "" end

dev = {}
dev.Type = devConfig:match("TAG_DEV_TYPE=(%x+)") or "08"
dev.Status = devConfig:match("TAG_DEV_STATUS=(%x+)") or "02"
dev.State = devConfig:match("TAG_DEV_STATE=(%x+)") or "03"
dev.Label = devConfig:match([[TAG_DEV_LABEL=%"(.-)%"]]) or "unknown"
dev.Version = devConfig:match([[TAG_VERSION=(%x+)]]) or ""
dev.NAnalogIn = devConfig:match([[TAG_DEV_NANALOGINPUT=(%x+)]]) or ""
dev.NAnalogOut = devConfig:match([[TAG_DEV_NANALOGOUTPUT=(%x+)]]) or ""
dev.NDiscIn = devConfig:match([[TAG_DEV_NDISCINPUT=(%x+)]]) or ""
dev.NDiscOut = devConfig:match([[TAG_DEV_NDISCOUTPUT=(%x+)]]) or ""

content = ""

content = content .. [[
                    <div id="info">
                        <center><h1>]]..siteLabel..[[ / ]]..dev.Label..[[</h1></center>
                    </div>
]]

if (userLevel == 1) then
    content = content .. [[
                    <center><b>Note:</B> Editing this section requires administrator privileges.</center><br>
]]                    
end

if (siteConfig == "") or (devConfig == "") then
    -- Bail on error
    content = content .. [[
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"/> Invalid response</h2>
                            The RSM client ]]..rsm_conf.rsmc_path..[[ is missing, not responding or returned an invalid reply.<br>
                            This may happen if the site is currently experiencing a lot of traffic.<br><br>
                            <a href="rsm_devices.lua">Back to devices</a>
                        </center>
                    </div>
]]
    print(header..content..footer)
    return
end

option1 = "" -- This is for "unknown"
option2 = "" -- DISCOVERED
option3 = "" -- MAINTENANCE
option4 = "" -- OPERATIONAL

if dev.State == "00" then -- DISCOVERED
    option2 = " selected"
elseif dev.State == "01" then
    option3 = " selected" -- MAINTENANCE
elseif dev.State == "02" then
    option4 = " selected" -- OPERATIONAL
else
    option1 = " selected" -- "unknown"
end

content = content .. [[
                    <script>

                        var xmlhttp;
                        var clicked = 0;
                        var xmlHttpTimeout;

                        function loadXMLDoc(url,cfunc)
                        {
                            if (window.XMLHttpRequest)
                            {// code for IE7+, Firefox, Chrome, Opera, Safari
                                xmlhttp=new XMLHttpRequest();
                            }
                            else
                            {// code for IE6, IE5
                                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            xmlhttp.onreadystatechange=cfunc;
                            xmlhttp.open("POST",url,true);
                            xmlhttp.send();
                            // Timeout to abort in 3 seconds
                            xmlHttpTimeout=setTimeout(ajaxTimeout, 6000);
                            var spinner = document.getElementById("spinner");
                            spinner.innerHTML = "<br><b>Refreshing... </b><img src=\"images/spinner.gif\" width=\"20\" height=\"20\"/><br>";
                        }

                        function ajaxTimeout()
                        {
                            xmlhttp.abort();
                            var spinner = document.getElementById("spinner");
                            spinner.innerHTML = "<b>Request timed out... </b><br>";
                            clicked = 0;
                            setTimeout(myFunction, 20000);
                        }
                        
                        function createTable(array, name)
                        {
                            if (array.length == 0)
                            {
                                return;
                            }
                            var div = document.getElementById("myDiv");
                            
                            var table = document.createElement("table");
                            table.id = name+"Table";
                            table.className = "onetwo";
                            table.style.textAlign="center";
                            
                            var header = table.createTHead();
                            var row=header.insertRow(0);
                            
                            var th = document.createElement("th");
                            th.style.width = "15%";
                            th.innerHTML = "PNum";
                            row.appendChild(th);
                            
                            th = document.createElement("th");
                            th.style.width = "35%";
                            th.innerHTML = "Label";
                            row.appendChild(th);
                            
                            th = document.createElement("th");
                            th.style.width = "30%";
                            th.innerHTML = "State";
                            row.appendChild(th);
                            
                            th = document.createElement("th");
                            th.style.width = "20%";
                            th.innerHTML = "Alarm State";
                            row.appendChild(th);
                            
                            //row.innerHTML = "<th width=\"15%\">PNum</th><th width=\"35%\">Label</th><th width=\"30%\">State</th><th width=\"20%\">Alarm State</th>";
                            
                            var idx;
                            for (idx = 0; idx < array.length; idx++)
                            {
                                //var port = array[array.length - idx - 1];
                                var port = array[idx];
                                var img = "images/"+name+"Unknown.png"; // Shouldn't happen
                                var style = "";
                                var text = "";
                                if (port.alarmStatus == "00")
                                {
                                    img = "images/"+name+".png";
                                    text = "CLEARED";
                                    background = "#90ff90"
                                }
                                else if (port.alarmStatus == "01")
                                {
                                    text = "SET";
                                    img = "images/"+name+"Alarm.png";
                                    background = "#ff9090"
                                }
                                else if (port.alarmStatus == "02")
                                {
                                    text = "WARNING";
                                    img = "images/"+name+"Alarm.png";
                                    background = "#ffffa0";
                                }
                                
                                var state = "UNKNOWN";
                                if (port.state == "00")
                                {
                                    state = "DISCOVERED";
                                }
                                else if (port.state == "01")
                                {
                                    state = "MAINTENANCE";
                                }
                                else if (port.state == "02")
                                {
                                    state = "OPERATIONAL";
                                }
                                var row = table.insertRow(idx+1);
                                row.id = name+idx;
                                //row.innerHTML = "<td>"+port.pnum+"</td><td>"+port.label+"</td><td>"+state+"</td><td id=\""+name+idx+"alarm\" style=\""+style+"\">"+text+" <img src=\""+img+"\" height=\"20\"/></td>";
                                
                                var td = document.createElement("td");
                                td.style.width = "15%";
                                td.innerHTML = port.pnum;
                                row.appendChild(td);
                                
                                td = document.createElement("td");
                                td.style.width = "35%";
                                td.innerHTML = port.label;
                                row.appendChild(td);
                                
                                td = document.createElement("td");
                                td.style.width = "30%";
                                td.innerHTML = state;
                                row.appendChild(td);
                                
                                td = document.createElement("td");
                                td.id = name+idx+"alarm";
                                td.style.backgroundColor = background;
                                td.style.width = "20%";
                                td.innerHTML = text+" <img src=\""+img+"\" height=\"20\"/>";
                                row.appendChild(td);
                            }
                            
                            var title = document.createElement("h3");
                            if (name == "output")
                            {
                                title.innerHTML = "Digital Output Ports:";
                                title.id = "outputTitle";
                            }
                            else if (name == "input")
                            {
                                title.innerHTML = "Digital Input Ports:";
                                title.id = "inputTitle";
                            }
                            else if (name == "analog")
                            {
                                title.innerHTML = "Analog Input Ports:";
                                title.id = "analogTitle";
                            }
                            else if (name == "analogout")
                            {
                                title.innerHTML = "Analog Output Ports:";
                                title.id = "analogOutTitle";
                            }
                            
                            div.appendChild(title);
                            div.appendChild(table);
                            //div.appendChild(document.createElement("br"));
                        }

                        function updateTables(oldArray, array, name)
                        {
                            if (array.length != oldArray.length)
                            {
                                /*
                                // Number of ports has changed somehow. Redraw the fucking table
                                var div = document.getElementById("myDiv");
                                var table = document.getElementById(name+"Table");
                                var title = document.getElementById(name+"Title");
                                if (table != null)
                                {
                                    myDiv.removeChild(table);
                                }
                                if (title != null)
                                {
                                    myDiv.removeChild(title);
                                }
                                createTable(array, name);
                                */
                                var div = document.getElementById("myDiv");
                                div.innerHTML = "";
                                oldObj = null;
                            }
                            else
                            {
                                var count = array.length;
                                var idx;
                                for (idx = 0; idx < count; idx++)
                                {
                                    //var port = array[count - idx - 1];
                                    var port = array[idx];
                                    //var oldPort = oldArray[count - idx - 1];
                                    var oldPort = oldArray[idx];
                                    
                                    // State changed
                                    if (port.alarmStatus != oldPort.alarmStatus)
                                    {
                                        // Did it change from clear or warning to set?
                                        if (port.alarmStatus == "01")
                                        {
                                            var alarm = document.getElementById(name+idx+"alarm");
                                            alarm.innerHTML = "SET <img src=\"images/"+name+"Alarm.png\" height=\"20\"/>"
                                            alarm.style.backgroundColor = "#ff9090"
                                        }
                                        else if (port.alarmStatus == "00") // Changed from set or warning to clear
                                        {
                                            var alarm = document.getElementById(name+idx+"alarm");
                                            // Mark as cleared
                                            alarm.setAttribute("cleared",true);
                                            alarm.innerHTML = "CLEARED <img src=\"images/"+name+".png\" height=\"20\"/>"
                                            alarm.style.backgroundColor = "#9090ff"
                                        }
					else if (port.alarmStatus == "02") // Changed from set or clear to warning
                                        {
                                            var alarm = document.getElementById(name+idx+"alarm");
                                            alarm.innerHTML = "WARNING <img src=\"images/"+name+"Alarm.png\" height=\"20\"/>"
                                            alarm.style.backgroundColor = "#ffffa0"
                                        }
                                    }
                                    else // Didn't change, but was it cleared?
                                    {
                                        var alarm = document.getElementById(name+idx+"alarm");
                                        if (alarm.getAttribute("cleared"))
                                        {
                                            alarm.removeAttribute("cleared");
                                            alarm.style.backgroundColor = "#90ff90"
                                        }
                                    }
                                }
                            }
                        }

                        var oldObj = null;
                        function handleIt(obj)
                        {
                            var div = document.getElementById("myDiv");
                            var spinner = document.getElementById("spinner");
                            spinner.innerHTML = "";
                            if (oldObj == null)
                            {
                                jsonObj = JSON.parse(obj);
                                createTable(jsonObj.outputPorts, "output");
                                createTable(jsonObj.inputPorts, "input");
                                createTable(jsonObj.analogPorts, "analog");
                                createTable(jsonObj.analogOutPorts, "analogout");
                            }
                            else
                            {
                                // Have to figure out what changed
                                var jsonObj = JSON.parse(obj);
                                var oldJsonObj = JSON.parse(oldObj);
                                updateTables(oldJsonObj.outputPorts, jsonObj.outputPorts, "output");
                                updateTables(oldJsonObj.inputPorts, jsonObj.inputPorts, "input");
                                updateTables(oldJsonObj.analogPorts, jsonObj.analogPorts, "analog");
                                updateTables(oldJsonObj.analogOutPorts, jsonObj.analogOutPorts, "analogout");
                                if (oldObj == null)
                                {
                                    handleIt(obj);
                                }
                            }
                            oldObj = obj;
                        }

                        function myFunction()
                        {
                            if (clicked == 1)
                            {
                                return;
                            }
                            else
                            {
                                clicked = 1;
                            }
                            loadXMLDoc("rsm_device_ports_ajax.lua?devID=]]..devID..[[", function()
                            {
                                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                                {
                                    clearInterval(xmlHttpTimeout);
                                    //document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
                                    handleIt(xmlhttp.responseText)
                                    clicked = 0;
                                    setTimeout(myFunction, 10000);
                                }
                                if (xmlhttp.readyState==4 && xmlhttp.status==404)
                                {
                                    clearInterval(xmlHttpTimeout);
                                    document.getElementById("myDiv").innerHTML="<b>Error 404</b>";
                                    clicked = 0;
                                }
                            });
                        }
                    </script>

                    <table class="onetwo" style="text-align: center;">
                        <tr>
                            <td width="17%"><a title="Configure device" href="rsm_device_edit.lua?devID=]]..devID..[[">Device Config</a></td>
                            <td width="16%" style="background-color: #f0f0f0;"><b>Ports <img src="images/magnify.png"/></b></td>
                            <td width="16%"><a title="Configure digital inputs" href="rsm_device_inputs.lua?devID=]]..devID..[[">Inputs <img src="images/spanner.png"/></a></td>
                            <td width="16%"><a title="Configure digital outputs" href="rsm_device_outputs.lua?devID=]]..devID..[[">Outputs <img src="images/spanner.png"/></a></td>
                            <td width="16%"><a title="Configure analog inputs" href="rsm_device_analog.lua?devID=]]..devID..[[">Analog Inputs<img src="images/spanner.png"/></a></td>
                            <td width="16%"><a title="Configure analog outputs" href="rsm_device_analog_out.lua?devID=]]..devID..[[">Analog Outputs<img src="images/spanner.png"/></a></td>
                        </tr>
                    </table>
                    <br>
                    <div class="formLayoutfull">
                        <div id="myDiv">
                        </div>
                        <span id="spinner"></span>
                    </div>
                    <script>
                        myFunction();
                    </script>
]]

print(header..content..footer)
