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

content = ""

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"] = "VEEDER_ROOT"
typeStrings["08"] = "CAMERA"
typeStrings["09"] = "OTHER"
typeStrings["0A"] = "UNKNOWN"

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

if (cgi.post.saveButton == "Save and Apply") and (userLevel ~= 1) then
    newLabel = cgi.post.label or "unknown"
    newState = cgi.post.state or "00"
    command.ex(rsm_conf.rsmc_path..[[ SET: TAG_DEV_CFG TAG_DEV_ID=]]..devID..[[ TAG_DEV_LABEL="]]..newLabel..[[" TAG_DEV_STATE=]]..newState)
    saved = 1
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 ""
devCap = command.ex(rsm_conf.rsmc_path..[[ GET: TAG_CAP_DEF 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 "0A"
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 ""

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

devCap=devCap:gsub("TAG_CAP_DEF","# @")
devCap=devCap.." #"
caps = {}
count = 0
for capCfg in devCap:gmatch([[@ (.-) #]]) do
   cap =  {}
   cap.label = capCfg:match([[TAG_CAP_LABEL=%"(.-)%"]]) or ""
   cap.value = capCfg:match([[TAG_CAP_VALUE=%"(.-)%"]]) or ""
   caps[count] = cap
   count = count + 1
end 

swopControl = ""
if (userLevel == 1) then
    swopControl = " disabled"
else
    if (dev.State ~= "01") or (dev.Status ~= "00") then swopControl = " disabled" end
end

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

if (cgi.post.deleteButton == "Delete Device") and (userLevel ~= 1) then
    command.ex(rsm_conf.rsmc_path..[[ DEL: TAG_DEV_CFG TAG_DEV_ID=]]..devID)
    content = content .. [[
                    <div id="info">
                        <center>
                            <h2>Device Deleted</h2>
                            <b>The device "]]..dev.Label..[[" with serial ]]..devID..[[ has been deleted.<br><br>
                            <a href="rsm_devices.lua">Back to devices</a>
                        </center>
                    </div>
]]
    print(header..content..footer)
    os.exit()
end

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 .. [[
                    <table class="onetwo" style="text-align: center;">
                        <tr>
                            <td width="17%" style="background-color: #f0f0f0;"><b>Device Config</b></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%"><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>
                    <center><b>Note:</b> To view the status of ports (alarms) or configure IOs, use the menu above.<br></center>
                    <br>
                    <div class="formLayoutfull">
                        <h3>Device Configuration:</h3>
                        <form action="rsm_device_edit.lua" method="post">
                            <ul>
                                <li><label style="display: inline-block; width: 150px;">Device Serial: </label> ]] .. devID .. [[</li>
                                <li><label style="display: inline-block; width: 150px;">Device Label: </label> <input type="text" name="label" value="]] .. dev.Label .. [["]]..inputControl..[[/></li>
                                <li><label style="display: inline-block; width: 150px;">Type: </label> ]] .. typeStrings[dev.Type] .. [[</li>
                                <li>
                                    <label style="display: inline-block; width: 150px;">State: </label>
                                    <select name="state"]]..buttonControl..[[>
                                        <option value="unknown" disabled]]..option1..[[>UNKNOWN</option>
                                        <option value="00"]]..option2..[[>DISCOVERED</option>
                                        <option value="01"]]..option3..[[>MAINTENANCE</option>
                                        <option value="02"]]..option4..[[>OPERATIONAL</option>
                                    </select>
                                </li>
                                <li><label style="display: inline-block; width: 150px;">Status: </label> ]] .. statusStrings[dev.Status] .. [[</li>
                                <li><label style="display: inline-block; width: 150px;">Version: </label> ]] .. dev.Version .. [[</li>
                            </ul>
                      
]]                               
                                 
                                   
content = content .. [[
                            <input type="hidden" name="devID" value="]]..devID..[["/></li>
                            <hr><br>
]]
if (saved == 1) then
    content = content .. [[
                            <b><img src="images/ok.png"/> Changes saved.</b><br><br>
]]
end
content = content .. [[
                            <input type="button" name="backButton" value="Back to Devices" onclick="window.location.assign('rsm_devices.lua');"/>
                            <input type="submit" value="Save and Apply" name="saveButton"]]..buttonControl..[[/>
                            <input type="submit" value="Delete Device" name="deleteButton"]]..buttonControl..[[ onclick="return confirm('Are you sure you want to delete this device?');"/>
                            <input type="button" value="Swop Device" name="swopButton"]]..swopControl..[[ onclick="window.location.assign('rsm_device_swop.lua?devID=]]..devID..[[');"/>
                        </form>
                        <h3>Device Details:</h3>
                        <ul>
]]                        
    for idx,cfg in pairs(caps) do
       content = content .. [[<li><label style="display: inline-block; width: 150px;">]]..cfg.label..[[: </label> ]]..cfg.value..[[</li> ]]
    end
content = content ..[[    </ul
                    </div>
]]
  

print(header..content..footer)
