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
saved = 0
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"

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

if (devConfig:match("TAG_DEV_ID=(%x+)") ~= devID) then devConfig = "" end
count = 0
if (analogsConfig:match("TAG_AO_CFG")) then
    analogs = {}
    for analogCfg in analogsConfig:gmatch([[TAG_AO_CFG (.-) TAG_IO_TYPE]]) do
        analog = {}
        analog.type = "04"
        analog.pnum = analogCfg:match([[TAG_IO_PNUM=(%x+)]]) or ""
        analog.devID = devID
        analog.label = analogCfg:match([[TAG_IO_LABEL="(.-)"]]) or ""
        analog.status = analogCfg:match([[TAG_IO_STATUS=(%x+)]]) or "03"
        analog.calculatedValue = analogCfg:match([[TAG_AO_OUTPUT_VALUE=([^ ]+)]]) or "0" 
        analog.unit = analogCfg:match([[TAG_AO_DISPLAY_UNIT="(.-)"]]) or ""        
        idx = tonumber(analog.pnum,16)
        if idx > count then
          count = idx
        end
        analogs[idx] = analog

    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.status = cgi.post["status"..counter] or "00"
            if analogs[counter].status ~= input.status then
              analogs[counter].status = input.status
              cmd = rsm_conf.rsmc_path .. " SET:"
              cmd = cmd .. [[ TAG_AO_CFG ]]
              cmd = cmd .. [[ TAG_DEV_ID=]]..devID
              cmd = cmd .. [[ TAG_IO_PNUM=]]..input.pnum
              cmd = cmd .. [[ TAG_IO_STATUS=]]..input.status
              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>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%"><a title="Configure analog inputs" href="rsm_device_analog.lua?devID=]]..devID..[[">Analog Inputs<img src="images/spanner.png"/></a></td>
                            <td width="16%" style="background-color: #f0f0f0;">Analog Outputs<img src="images/spanner.png"/></td>
                        </tr>
                    </table>
                    <br>
                    <div class="formLayoutfull">
                        <h3>Analogue Outputs:</h3>
]]

if (analogs ~= nil) then
    content = content .. [[
                        <form action="rsm_device_analog_out.lua" method="post">
                        <table class="onetwo" style="text-align: center;">
                            <tr>
                                <th>PNum</th>
                                <th>Label</th>
                                <th>Status</th>
                                <th>Output Value</th>
                            </tr>
]]

  idx = 0
  option1 = {}
  option2 = {}
  option3 = {}
  option4 = {}
  for idx = count,1,-1 do
     if analogs[idx] ~= nil then
        option1[idx] = ""
        option2[idx] = ""
        option3[idx] = ""
        option4[idx] = ""
        if analogs[idx].status == "00" then
            option2[idx] = " selected"
        elseif analogs[idx].status == "01" then
            option3[idx] = " selected"
        elseif analogs[idx].status == "02" then
            option4[idx] = " selected"
        else
            option1[idx] = " selected"
        end
     end
  end
  
    idx = 0
    for idx = 1,count do

    -- @changed: 14 May 2014
    -- @author: fvdl
    -- @desc: 
    -- Lua 5.2 string.format does not like being handed Strings
    -- Store the value temporarily and convert if NOT 'nan'
      if analogs[idx] ~= nil then
     
         local temp_value = analogs[idx].calculatedValue
         if temp_value ~= "nan" then
             temp_value = string.format("%.1f", analogs[idx].calculatedValue)
         end

        content = content .. [[
                            <tr>
                                <td>]]..tonumber(analogs[idx].pnum,16)..[[</td>
                                <td><a href="rsm_device_analog_out_edit.lua?devID=]]..devID..[[&pnum=]]..analogs[idx].pnum..[[">]]..analogs[idx].label..[[ <img src="images/spanner.png"/></a></td>
                                <td>
                                      <select style="float: center;" name="status]]..idx..[["]]..buttonControl..[[>
                                          <option value="03" disabled]]..option1[idx]..[[>UNKNOWN</option>
                                          <option value="00"]]..option2[idx]..[[>DISCOVERED</option>
                                          <option value="01"]]..option3[idx]..[[>MAINTENANCE</option>
                                          <option value="02"]]..option4[idx]..[[>OPERATIONAL</option>
                                      </select>
                                </td>
                                <td>]]..temp_value.." "..analogs[idx].unit..[[</td>
                            </tr>
                            <input type="hidden" name="pnum]]..idx..[[" value="]]..analogs[idx].pnum..[["/>
]]
       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 analogue outputs. ]]
end  


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

print(header..content..footer)
