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

bus = cgi.get.bus or ""

serialConfig = command.ex([[cat ]]..rsm_conf.serialconfig_path) or ""

naradadConfig = command.ex([[cat ]]..rsm_conf.naradad_conf_path) or ""
if (naradadConfig ~= "") then
    naradadPath = naradadConfig:match([[naradad.device.dir=(.*)%$]]) or "/etc/rsm/naradad/devices/"
    if (naradadPath ~= "") then
        naradadFiles = {}
        naradadFiles = command.getFilesInTable(naradadPath)
    end
end

deviceConfs = {}
if (naradadFiles) then
    for i,f in pairs(naradadFiles) do
        temp = command.ex([[cat ]]..naradadPath..[[/]]..f) or ""
        if temp:match([[<port>%s-]]..bus..[[%s-</port>]]) then
            table.insert(deviceConfs, [[Filename: ]]..f..[[\n]]..temp)
        end
    end
end

devices = {}
for i,cfg in pairs(deviceConfs) do
    d = {}
    d.filename = cfg:match([[Filename:%s+(.-)%s-\n]])
    d.label = cfg:match([[<label>%s-(.-)%s-</label>]]) or "unknown"
    d.serial = cfg:match([[<serial>%s-(.-)%s-</serial>]]) or "unknown"
    d.port = cfg:match([[<port>%s-(.-)%s-</port>]]) or bus
    d.owner = cfg:match([[<owner>%s-(.-)%s-</owner>]]) or "naradad"
    d.config = cfg:match([[<config>%s-(.-)%s-</config>]]) or rsm_conf.serialconfig_path
    table.insert(devices,d)
end

dev, busConfig = serialConfig:match([[<port%s+device=%"(]]..bus..[[)%"%s->(.-)</port>]])

if (dev == bus) and (busConfig ~= nil) then
    if busConfig:match("<owner>%s-naradad%s-</owner>") == nil then
        mismatch = 1
    else
        mismatch = 0
    end
else
    mismatch = 1
end

content = ""

content = content .. [[
                    <div id="info">
                        <div style="background:url(images/busconfig.png); background-size:32px; background-repeat:no-repeat; background-position: 20px center;">
                            <center><h1>Narada Configuration</h1></center>
                        </div>
                    </div>
]]

if (mismatch == 1) then
    -- Bail on error here
    content = [[
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"/> Invalid bus</h2>
                            Either an invalid bus was specified, or the bus cannot be matched<br>
                            to a valid ModBus entry in the serial config file "]]..rsm_conf.serialconfig_path..[[".<br><br>
                            <a href="rsm_bus_config.lua">Back to bus configuration</a>
                        </center>
                    </div>
]]
    html = header..content..footer
    print(html)
    os.exit()
end


content = content .. [[
                    <b><br>
                    <center>
                        This is a list of all Narada devices on ]]..bus..[[<br><br>
                        Click on the device labels to manage them.</b>
                    </center><br>                                        
                    <div>

]]

if (userLevel == 1) then
    content = content .. [[
                    <center><b>Note:</b> Editing this section requires administrator privileges.</center><br>
]]
end

if (#(devices) > 0) then
    content = content .. [[

                        <table class="onetwo" style="text-align: center;">
                            <tr>
                                <th>Label</th>
                                <th>Device Serial</th>
                            </tr>
]]
    for i,dev in pairs(devices) do
        content = content .. [[
                            <tr>
                                <td style="text-align: left;"><a href="rsm_naradad_edit.lua?file=]]..dev.filename..[[&bus=]]..dev.port..[[">]]..dev.label..[[<img src="images/spanner.png" style="float: right;"></a></td>
                                <td>]]..dev.serial..[[</td>
                            </tr>

]]
    end
    content = content .. [[
                        </table>
]]
else
    content = content .. [[
                        <div class="formLayoutfull">
                            <center><b>There are no Narada devices configured on this bus.</b></center>
                        </div>
]]        
end

content = content .. [[
                        <br>
                        <form action="rsm_naradad_edit.lua" method="post">
                            <input type="hidden" value="]]..bus..[[" name="bus"/>
                            <input type="button" value="Back to Bus Configuration" onclick="window.location.assign('rsm_bus_config.lua');"/>
                            <input type="submit" name="addButton" value="Add Narada Device"]]..buttonControl..[[/>
                        </form>
                    </div>
]]

print(header..content..footer)
