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

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

if (cgi.post.saveButton == "Save and Apply") and (userLevel ~= 1) then
    input = {}
    input.pnum = cgi.post["pnum"] or "00"
    input.label = cgi.post["label"] or "UNKNOWN"
    input.status = cgi.post["status"] or "00"
    input.offset = cgi.post["offset"] or "0"
    input.gain = cgi.post["gain"] or "0"
    input.sampleRate = cgi.post["sampleRate"] or "0"
    input.reportRate = cgi.post["reportRate"] or "0"
    input.lowWarn = cgi.post["lowWarn"] or "0"
    input.highWarn = cgi.post["highWarn"] or "0"
    input.lowErr = cgi.post["lowErr"] or "0"
    input.highErr = cgi.post["highErr"] or "0"
    input.sampleRate = string.format("%08X", tonumber(input.sampleRate))
    input.reportRate = string.format("%08X", tonumber(input.reportRate))
    input.unit = cgi.post["unit"] or ""
    input.acceptableNoise = cgi.post["acceptableNoise"] or "0"

    cmd = rsm_conf.rsmc_path .. " SET:"
    cmd = cmd .. [[ TAG_AI_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_GAIN=]]..input.gain
    cmd = cmd .. [[ TAG_IO_OFFSET=]]..input.offset
    cmd = cmd .. [[ TAG_AI_SAMPLE_RATE=]]..input.sampleRate
    cmd = cmd .. [[ TAG_AI_REPORT_RATE=]]..input.reportRate
    cmd = cmd .. [[ TAG_AI_ALARM_LOW_WARN=]]..input.lowWarn
    cmd = cmd .. [[ TAG_AI_ALARM_HIGH_WARN=]]..input.highWarn
    cmd = cmd .. [[ TAG_AI_ALARM_LOW_ERR=]]..input.lowErr
    cmd = cmd .. [[ TAG_AI_ALARM_HIGH_ERR=]]..input.highErr
    cmd = cmd .. [[ TAG_AI_DISPLAY_UNIT="]]..input.unit..[["]]
    cmd = cmd .. [[ TAG_AI_ACCEPTABLE_NOISE=]]..input.acceptableNoise
    command.ex(cmd)
    
    saved = 1
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"
analogCfg = command.ex(rsm_conf.rsmc_path..[[ GET: TAG_AI_CFG TAG_DEV_ID=]]..devID..[[ TAG_IO_PNUM=]]..pnum) or "" 

if (devConfig:match("TAG_DEV_ID=(%x+)") ~= devID) then devConfig = "" end
if (analogCfg:match("TAG_AI_CFG")) then
    analog = {}
    analog.type = "03" -- This is fixed
    analog.label = analogCfg:match([[TAG_IO_LABEL="(.-)"]]) or ""
    analog.pnum = analogCfg:match([[TAG_IO_PNUM=(%x+)]]) or ""
    analog.status = analogCfg:match([[TAG_IO_STATUS=(%x+)]]) or "03" 
    analog.sampledValue = analogCfg:match([[TAG_IO_SAMPLED_VALUE=([^ ]+)]]) or "0" 
    analog.offset = analogCfg:match([[TAG_IO_OFFSET=([^ ]+)]]) or "0"
    analog.gain = analogCfg:match([[TAG_IO_GAIN=([^ ]+)]]) or "0"
    analog.calculatedValue = analogCfg:match([[TAG_AI_CALCULATED_VALUE=([^ ]+)]]) or "0" 
    analog.lowWarn = analogCfg:match([[TAG_AI_ALARM_LOW_WARN=([^ ]+)]]) or "0" 
    analog.lowErr = analogCfg:match([[TAG_AI_ALARM_LOW_ERR=([^ ]+)]]) or "0" 
    analog.highWarn = analogCfg:match([[TAG_AI_ALARM_HIGH_WARN=([^ ]+)]]) or "0" 
    analog.highErr = analogCfg:match([[TAG_AI_ALARM_HIGH_ERR=([^ ]+)]]) or "0" 
    analog.sampleRate = analogCfg:match([[TAG_AI_SAMPLE_RATE=(%x+)]]) or "0" 
    analog.reportRate = analogCfg:match([[TAG_AI_REPORT_RATE=(%x+)]]) or "0" 
    analog.unit = analogCfg:match([[TAG_AI_DISPLAY_UNIT="(.-)"]]) or ""
    analog.acceptableNoise = analogCfg:match([[TAG_AI_ACCEPTABLE_NOISE=([^ ]+)]]) or "0" 
end

content = ""

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

if (analog == nil) then
    -- Bail on error
    content = content .. [[
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"/> Invalid device / pnum combo</h2>
                            Could not get a configuration for the specified device and analogue input pnum.<br><br>
                            <a href="rsm_devices.lua">Back to devices</a>
                        </center>
                    </div>
]]
    print(header..content..footer)
    return    
end


if (userLevel == 1) then
    content = content .. [[
                    <center>Note: 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%"><a title="Configure digital outputs" href="rsm_device_outputs.lua?devID=]]..devID..[[">Outputs <img src="images/spanner.png"/></a></td>
                            <td width="16%" style="background-color: #f0f0f0;">Analog Inputs<img src="images/spanner.png"/></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>Analogue Input ]]..tonumber(analog.pnum,16)..[[:</h3>
]]

content = content .. [[
                        <form action="rsm_device_analog_edit.lua" method="post">
]]
option1 = ""
option2 = ""
option3 = ""
option4 = ""
if analog.status == "00" then
    option2 = " selected"
elseif analog.status == "01" then
    option3 = " selected"
elseif analog.status == "02" then
    option4 = " selected"
else
    option1 = " selected"
end
        
content = content .. [[
                            <table class="onetwo">
                                <tr>
                                    <td colspan="2">Label:<input style="float: right;" type="text" name="label" value="]]..analog.label..[["]]..inputControl..[[/></td>
                                    <td colspan="2">Unit:<input style="float: right;" type="text" size="6" name="unit" value="]]..analog.unit..[["]]..inputControl..[[/></td>
                                </tr>
                                <tr>
                                    <td colspan="2">Sampled value:<span style="float: right; margin-right: 25px;">]]..analog.sampledValue..[[</span></td>
                                    <td colspan="2">Calculated value:<span style="float: right; margin-right: 25px;"><b>]]..analog.calculatedValue..[[</b></span></td>
                                </tr>
                                <tr>
                                    <td colspan="2">Status:
                                        <select style="float: right;" name="status"]]..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 colspan="2">Sensitivity (%):<input style="float: right;" type="text" size="6" name="acceptableNoise" value="]]..analog.acceptableNoise..[["]]..inputControl..[[/></td>
                                </tr>
                                <tr>
                                    <td>Gain:<input style="float: right;" type="text" size="6" name="gain" value="]]..analog.gain..[["]]..inputControl..[[/></td>
                                    <td>Offset:<input style="float: right;" type="text" size="6" name="offset" value="]]..analog.offset..[["]]..inputControl..[[/></td>
                                    <td>Sample rate (s):<input style="float: right;" type="text" size="6" name="sampleRate" value="]]..tonumber(analog.sampleRate,16)..[["]]..inputControl..[[/></td>
                                    <td>Report rate (min):<input style="float: right;" type="text" size="6" name="reportRate" value="]]..tonumber(analog.reportRate,16)..[["]]..inputControl..[[/></td>
                                </tr>
                                <tr>
                                    <td>Low error:<input style="float: right;" type="text" size="6" name="lowErr" value="]]..analog.lowErr..[["]]..inputControl..[[/></td>
                                    <td>Low warning:<input style="float: right;" type="text" size="6" name="lowWarn" value="]]..analog.lowWarn..[["]]..inputControl..[[/></td>
                                    <td>High warning:<input style="float: right;" type="text" size="6" name="highWarn" value="]]..analog.highWarn..[["]]..inputControl..[[/></td>
                                    <td>High error:<input style="float: right;" type="text" size="6" name="highErr" value="]]..analog.highErr..[["]]..inputControl..[[/></td>
                                </tr>
                            </table>
                            <input type="hidden" name="pnum" value="]]..analog.pnum..[["/>
                            <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="button" name="backButton" value="Back to Analog Inputs" onclick="window.location.assign('rsm_device_analog.lua?devID=]]..devID..[[');"/>
                            <input type="submit" name="saveButton" value="Save and Apply"]]..buttonControl..[[/>
                        </form>
                    </div>
]]

print(header..content..footer)
