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

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

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

stateStrings = {}
stateStrings["00"] = "LOW / OFF"
stateStrings["01"] = "HIGH / ON"
stateStrings["02"] = "UNKNOWN"

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 ""
devLabel = devConfig:match([[TAG_DEV_LABEL="(.-)"]]) or "unknown"
inputsConfig = command.ex(rsm_conf.rsmc_path..[[ GET: TAG_IP_CFG TAG_DEV_ID=]]..devID) or "" 


if (devConfig:match("TAG_DEV_ID=(%x+)") ~= devID) then devConfig = "" end
count = 0
if (inputsConfig:match("TAG_IP_CFG")) then
    inputs = {}
    for inputCfg in inputsConfig:gmatch([[TAG_IP_CFG (.-) TAG_IO_TYPE]]) do
        input = {}
        input.type = "01" -- This is fixed
        input.label = inputCfg:match([[TAG_IO_LABEL="(.-)"]]) or ""
        input.pnum = inputCfg:match([[TAG_IO_PNUM=(%x+)]]) or ""
        input.status = inputCfg:match([[TAG_IO_STATUS=(%x+)]]) or "03" 
        input.state = inputCfg:match([[TAG_IO_STATE=(%x+)]]) or "02"
        input.defaultState = inputCfg:match([[TAG_IO_DEFAULT_STATE=(%x+)]]) or "02"
        idx = tonumber(input.pnum,16)
        if idx > count then
          count = idx
        end
        inputs[idx] = input
    end
end

if (cgi.post.saveButton == "Save and Apply") and (userLevel ~= 1) then
    for counter = 1,count do
        if (cgi.post["pnum"..counter] ~= nil) then
            input = {}
            input.pnum = cgi.post["pnum"..counter] or "00"
            input.label = cgi.post["label"..counter] or "UNKNOWN"
            input.status = cgi.post["status"..counter] or "00"
            input.defaultState = cgi.post["defaultState"..counter] or "00"
            if (inputs[counter].status ~= input.status) or (inputs[counter].defaultState ~= input.defaultState) or (inputs[counter].label ~= input.label) then
              inputs[counter].status = input.status
              inputs[counter].defaultState = input.defaultState
              inputs[counter].label = input.label
              cmd = rsm_conf.rsmc_path .. " SET:"
              cmd = cmd .. [[ TAG_IP_CFG ]]
              cmd = cmd .. [[ TAG_DEV_ID=]]..devID
              cmd = cmd .. [[ TAG_IO_PNUM=]]..input.pnum
              cmd = cmd .. [[ TAG_IO_LABEL="]]..input.label
              cmd = cmd .. [[" TAG_IO_STATUS=]]..input.status
              cmd = cmd .. [[ TAG_IO_DEFAULT_STATE=]]..input.defaultState
              command.ex(cmd)
              if ((counter % 5) == 0) then command.ex("sleep 1") end
            end
        end
    end
    
    saved = 1
end

content = ""

content = content .. [[
                    <div id="info">
                        <center><h1>]]..siteLabel..[[ / ]]..devLabel..[[</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

content = content .. [[
                    <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%"><a title="Monitor port alarms" href="rsm_device_ports.lua?devID=]]..devID..[[">Ports<img src="images/magnify.png"/></a></td>
                            <td width="16%" style="background-color: #f0f0f0;"><b>Inputs <img src="images/spanner.png"/></b></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">
                        <h3>Digital Inputs:</h3>
]]

if (inputs ~= nil) then
    content = content .. [[
                        <form action="rsm_device_inputs.lua" method="post">
                            <table class="onetwo" style="text-align: center;">
                                <tr>
                                    <th width="10%">PNum</th>
                                    <th width="33%">Label</th>
                                    <th width="25%">Status</th>
                                    <th width="16%">State</th>
                                    <th width="16">Default State</th>
                                </tr>
]]
    idx = 0
    for idx = 0,count do
      if inputs[idx] ~= nil then
        option1 = ""
        option2 = ""
        option3 = ""
        option4 = ""
        if inputs[idx].status == "00" then
            option2 = " selected"
        elseif inputs[idx].status == "01" then
            option3 = " selected"
        elseif inputs[idx].status == "02" then
            option4 = " selected"
        else
            option1 = " selected"
        end
        
        defaultStateOption1 = ""
        defaultStateOption2 = ""
        defaultStateOption3 = ""
        
        if inputs[idx].defaultState == "00" then
            defaultStateOption2 = " selected"
        elseif inputs[idx].defaultState == "01" then
            defaultStateOption3 = " selected"
        else
            defaultStateOption1 = " selected"
        end
        
        content = content .. [[
                                <tr>
                                    <td>]]..tonumber(inputs[idx].pnum,16)..[[</td>
                                    <td><input type="text" size="25" name="label]]..idx..[[" value="]]..inputs[idx].label..[["]]..inputControl..[[/></td>
                                    <td>
                                        <select name="status]]..idx..[["]]..buttonControl..[[>
                                            <option value="03" disabled]]..option1..[[>UNKNOWN</option>
                                            <option value="00"]]..option2..[[>DISCOVERED</option>
                                            <option value="01"]]..option3..[[>MAINTENANCE</option>
                                            <option value="02"]]..option4..[[>OPERATIONAL</option>
                                        </select>
                                    </td>
                                    <td>]]..stateStrings[inputs[idx].state]..[[</td>
                                    <td>
                                        <select name="defaultState]]..idx..[["]]..buttonControl..[[>
                                            <option value="02" disabled]]..defaultStateOption1..[[>UNKNOWN</option>
                                            <option value="00"]]..defaultStateOption2..[[>LOW / OFF</option>
                                            <option value="01"]]..defaultStateOption3..[[>HIGH / ON</option>
                                        </select>
                                        <input type="hidden" name="pnum]]..idx..[[" value="]]..inputs[idx].pnum..[["/>
                                    </td>
                                </tr>
]]
       end
    end
    content = content .. [[
                            </table>
                            <br><hr><br>
]]
    if (saved == 1) then
        content = content .. [[
                            <b><img src="images/ok.png"/> Changes saved.</b><br><br>
]]
    end
    content = content .. [[
                            <input type="hidden" name="devID" value="]]..devID..[["/>
                            <input type="submit" name="saveButton" value="Save and Apply"]]..buttonControl..[[/>
                        </form>
]]
else
    content = content .. [[ This device does not have any discrete inputs. ]]
end    

content = content .. [[
                    </div>
]]

print(header..content..footer)
