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"
    outputControl = " readonly"
else
    buttonControl = ""
    outputControl = ""
end

devID = cgi.get.devID or cgi.post.devID or ""
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"

toggledStrings = {}
toggledStrings["00"] = "UNK"
toggledStrings["01"] = "NONE"
toggledStrings["02"] = "WEBSITE"
toggledStrings["03"] = "IO LOGIC"
toggledStrings["04"] = "CCD"

toggledTitleMessages = {}
toggledTitleMessages["00"] = "Unknown entity has set this port"
toggledTitleMessages["01"] = "Nothing has set this port"
toggledTitleMessages["02"] = "Website"
toggledTitleMessages["03"] = "IO Logic Engine"
toggledTitleMessages["04"] = "Climate Control"

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"
outputsConfig = command.ex(rsm_conf.rsmc_path..[[ GET: TAG_OP_CFG TAG_DEV_ID=]]..devID) or "" 

if (devConfig:match("TAG_DEV_ID=(%x+)") ~= devID) then devConfig = "" end
count = 0
if (outputsConfig:match("TAG_OP_CFG")) then
    outputs = {}
    for outputCfg in outputsConfig:gmatch([[TAG_OP_CFG (.-) TAG_IO_TYPE]]) do
        output = {}
        output.type = "02" -- This is fixed
        output.label = outputCfg:match([[TAG_IO_LABEL="(.-)"]]) or ""
        output.pnum = outputCfg:match([[TAG_IO_PNUM=(%x+)]]) or ""
        output.status = outputCfg:match([[TAG_IO_STATUS=(%x+)]]) or "03" 
        output.state = outputCfg:match([[TAG_IO_STATE=(%x+)]]) or "02"
        output.defaultState = outputCfg:match([[TAG_IO_DEFAULT_STATE=(%x+)]]) or "02"
        output.toggled = outputCfg:match([[TAG_PORT_LAST_TOGGLED=(%x+)]]) or "01"
        idx = tonumber(output.pnum,16)
        if idx > count then
          count = idx
        end
        outputs[idx] = output
    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
            output = {}
            output.pnum = cgi.post["pnum"..counter] or "00"
            output.label = cgi.post["label"..counter] or "UNKNOWN"
            output.status = cgi.post["status"..counter] or "00"
            output.defaultState = cgi.post["defaultState"..counter] or "00"
            output.state = cgi.post["state"..counter] or "00"
            output.toggled = "02"
                       
            if (outputs[counter].status ~= output.status) or (outputs[counter].state ~= output.state) or (outputs[counter].defaultState ~= output.defaultState) or (outputs[counter].label ~= output.label) then
              outputs[counter].status = output.status
              outputs[counter].defaultState = output.defaultState
              outputs[counter].label = output.label
              outputs[counter].state = output.state
              outputs[counter].toggled = output.toggled
              
              cmd = rsm_conf.rsmc_path .. " SET:"
              cmd = cmd .. [[ TAG_OP_CFG ]]
              cmd = cmd .. [[ TAG_DEV_ID=]]..devID
              cmd = cmd .. [[ TAG_IO_PNUM=]]..output.pnum
              cmd = cmd .. [[ TAG_IO_LABEL="]]..output.label
              cmd = cmd .. [[" TAG_IO_STATUS=]]..output.status
              cmd = cmd .. [[ TAG_IO_STATE=]]..output.state
              cmd = cmd .. [[ TAG_IO_DEFAULT_STATE=]]..output.defaultState
              cmd = cmd .. [[ TAG_PORT_LAST_TOGGLED=02]]
              command.ex(cmd)
              if ((counter % 3) == 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%"><a title="Configure digital inputs" href="rsm_device_inputs.lua?devID=]]..devID..[[">Inputs <img src="images/spanner.png"/></a></td>
                            <td width="16%" style="background-color: #f0f0f0;"><b>Outputs <img src="images/spanner.png"/></b></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 Outputs:</h3>
]]

if (outputs ~= nil) then
    content = content .. [[
                        <form action="rsm_device_outputs.lua" method="post">
                            <table class="onetwo" style="text-align: center;">
                                <tr>
                                    <th width="10%">PNum</th>
                                    <th width="22%">Label</th>
                                    <th width="16%">Status</th>
                                    <th width="20%" title="Last entitiy which set this port">Toggled By</th>
                                    <th width="16%">State</th>
                                    <th width="16">Default State</th>
                                </tr>
]]
    idx = 0
    for idx =0,count do
      if outputs[idx] ~= nil then
        option1 = ""
        option2 = ""
        option3 = ""
        option4 = ""
        
        if outputs[idx].status == "00" then
            option2 = " selected"
        elseif outputs[idx].status == "01" then
            option3 = " selected"
        elseif outputs[idx].status == "02" then
            option4 = " selected"
        else
            option1 = " selected"
        end
        
        defaultStateOption1 = ""
        defaultStateOption2 = ""
        defaultStateOption3 = ""
        
        if outputs[idx].defaultState == "00" then
            defaultStateOption2 = " selected"
        elseif outputs[idx].defaultState == "01" then
            defaultStateOption3 = " selected"
        else
            defaultStateOption1 = " selected"
        end
        
        stateOption1 = ""
        stateOption2 = ""
        stateOption3 = ""
        
        if outputs[idx].state == "00" then
            stateOption2 = " selected"
        elseif outputs[idx].state == "01" then
            stateOption3 = " selected"
        else
            stateOption1 = " selected"
        end

        content = content .. [[
                                <tr>
                                    <td>]]..tonumber(outputs[idx].pnum,16)..[[</td>
                                    <td><input type="text" size="25" name="label]]..idx..[[" value="]]..outputs[idx].label..[["]]..outputControl..[[/></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 size = 5 title="]]..toggledTitleMessages[outputs[idx].toggled]..[[">]]..toggledStrings[outputs[idx].toggled]..[[</td>
                                    <td>
                                        <select name="state]]..idx..[["]]..buttonControl..[[>
                                            <option value="02" disabled]]..stateOption1..[[>UNKNOWN</option>
                                            <option value="00"]]..stateOption2..[[>LOW / OFF</option>
                                            <option value="01"]]..stateOption3..[[>HIGH / ON</option>
                                        </select>
                                    </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="]]..outputs[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 outputs. ]]
end    

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

print(header..content..footer)
