require("luamods/command")
require("luamods/layout")
require("luamods/cgi")
require("config/rsm_conf")
require("luamods/rsm_serials")

header = layout.getHeader()
footer = layout.getFooter()

userLevel = db.getPriv(layout.username) or 1

function log(m)
   command.ex([[logger -t webconfig ]]..[["]]..m..[["]])
end

if (userLevel == 1) then
    buttonControl = " disabled"
    inputControl = " readonly"
else
    buttonControl = ""
    inputControl = ""
end

serialConfig = command.ex([[cat ]]..rsm_conf.serialconfig_path) or ""
ck200Config = command.ex([[cat ]]..rsm_conf.ck200_conf_path) or ""
if (ck200Config ~= "") then
    ck200Path = ck200Config:match([[ck200.device.dir=(.*)%$]]) or "/etc/rsm/ck200/devices"
    
    if (ck200Path ~= "") then
        ck200Files = command.getFilesInTable(ck200Path)
    end
end

if (cgi.post.deleteButton == "Delete Device") and (userLevel ~= 1) then
    file = cgi.post.file or ""

    --Physically check if dir is empty or not
    if (file=="") then
    
        local popen = io.popen
        local pfile = popen('ls -a "'..ck200Path..'"')
        for filename in pfile:lines() do
            if(string.match(filename,'.') ~= "." or not string.match(filename,'..') == "..")then
                file = filename
                log([[file: ]]..file)
            end
        end

        --if file is still empty
        
        if(file=="")then
    
            content = [[
                    <div id="info">
                        <center><h1>Delete TK1 Device</h1></center>
                    </div>
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"/> Nothing to Delete</h2>
                            No device to delete<br><br>
                            <a href="rsm_bus_config.lua?bus=Back to bus configuration">Back to bus configuration</a>
                        </center>
                    </div>

                    ]]

                    print(header..content..footer)
                    os.exit()
        end


    end

    file = file:gsub("[^%w%.]+","")
    command.ex([[rm ]]..ck200Path..[[/]]..file)
    label = cgi.post.label or "unknown"
    bus = cgi.post.bus or "unknown"

    command.ex(rsm_conf.ck200_restart)

    content = [[
                    <div id="info">
                        <center><h1>Delete TK1 Device</h1></center>
                    </div>
                    <div id="info">
                        <center>
                            <h2><img src="images/ok.png"/> Device Deleted</h2>
                            Device with filename "]]..file..[[" has been removed.<br><br>
                            <a href="rsm_bus_config.lua?bus=]]..bus..[[">Back to bus configuration</a>
                        </center>
                    </div>
]]
    print(header..content..footer)
    os.exit()
end

if (cgi.post.saveButton == "Create Device") and (userLevel ~= 1) then
    newFile = cgi.post.file or ""

    device_files = command.getFilesInTable(ck200Path)

    if next(device_files)~= nil then
    
        content = [[
                    <div id="info">
                        <center><h1>TK1 Device Info</h1></center>
                    </div>
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"/> Invalid </h2>
                            A TK1 device already exists.<br><br>
                            <a href="rsm_bus_config.lua">Back to bus configuration</a>
                        </center>
                    </div>
]]
        print(header..content..footer)
        os.exit()
    end

    if (newFile == "") then
        
        -- Generate serial for the ck200 device
        newDevice = rsm_serials.generateNewSerial()
        newFile = newDevice..".xml"
    
    end
    
    newPort = cgi.post.bus or "unknown"
    newOwner = "ck200"
    newXML = [[
<!-- ]]..ck200Path..[[/]]..newFile..[[ generated by webconfig -->
<CK200>
        <port>]]..newPort..[[</port>
        <serial>]]..newDevice..[[</serial>
        ]].."\n"
  
        newXML = newXML..[[

</CK200>
<!-- end of file -->
]]
    command.writefile(ck200Path..[[/]]..newFile, newXML)
    filename = newFile
    saved = 1
    mode = "edit"
    
    command.ex(rsm_conf.ck200_restart)

else
    filename = cgi.get.file or ""
    if (filename == "") then
        mode = "new"
    else
        mode = "edit"
    end
    
    --command.ex(rsm_conf.ck200_restart)

end

bus = cgi.get.bus or cgi.post.bus or ""

if (mode == "edit") then

    cfg = command.ex([[cat ]]..ck200Path..[[/]]..filename) or ""
    if (cfg:match("<CK200>(.+)</CK200>") == nil) then
        -- bail on error
        content = [[
                    <div id="info">
                        <center><h1>Edit TK1 Device</h1></center>
                    </div>
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"/> Invalid file</h2>
                            The specified file does not appear to be a valid TK1 device file.<br><br>
                            <a href="rsm_bus_config.lua">Back to bus configuration</a>
                        </center>
                    </div>
]]
        print(header..content..footer)
        os.exit()
    else
        d = {}
        d.serial = cfg:match([[<serial>%s-(.-)%s-</serial>]]) or "unknown"
        --log(d.master)
        d.port = cfg:match([[<port>%s-(.-)%s-</port>]])
        if (d.port ~= bus) then
            -- bail on error
            content = [[
                    <div id="info">
                        <center><h1>Edit TK1 Device</h1></center>
                    </div>
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"/> Device / bus mismatch</h2>
                            The device being edited is not on the currently selected bus.<br><br>
                            <a href="rsm_bus_config.lua">Back to bus configuration</a>
                        </center>
                    </div>
]]
            print(header..content..footer)
            os.exit()
        end
        d.owner = "ck200"
    end
else
    d = {}
    d.serial = "(unassigned)"
    d.port = bus
    d.owner = "ck200"
    
end

content = ""

if (mode == "new") then
    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> TK1 Device Config</h1></center>
                        </div>
                    </div>
]]
else
    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>TK1 Device Config</h1></center>
                        </div>
                    </div>
                    <h3>New device filename: "]]..filename..[[" :</h3>
]]
end

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 TK1 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

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

content = content .. [[
                    <script>
                        //var doValidate = 0;
                        function validateForm(form)
                        {

                            if (form.getAttribute('submitted')) return false;

                            if (!doValidate)
                            {
                                form.setAttribute('submitted','true');
                                return true;
                            }
                            doValidate = 0;

                            var inputs = form.getElementsByTagName("input");

                            var inputIdx;
                            var errors = 0;
                            for (inputIdx = 0; inputIdx < inputs.length; inputIdx++)
                            {
                                // Don't validate buttons.
                                if(inputs[inputIdx].type != "text")
                                  continue;
                            }

                        }
                    </script>
]]

if (mode == 'edit') then
    content = content .. [[
    
                        <div class="formLayoutfull">
                            <form action="rsm_ck200_config.lua" method="post" onsubmit="return validateForm(this);">
                                <h3>Device serial: ]] .. d.serial .. [[</h3>
                                
                        ]]

                    
                    else
                        
                        local popen = io.popen
                        local pfile = popen('ls -a "'..ck200Path..'"')
                        local file_status=""
                        for filename in pfile:lines() do
                            if(string.match(filename,'.') ~= "." or not string.match(filename,'..') == "..")then
                                file_status = [[Device file: ]]..filename
                                
                            else
                                file_status = "No Device detected"
                            end
                        end
    
                        content = content .. [[
    
                        <div class="formLayoutfull">
                            <form action="rsm_ck200_config.lua" method="post" onsubmit="return validateForm(this);">
                                <h3>]]..file_status..[[</h3>
                        ]]

    
end
    
if (saved == 1) then
    if (createdNew == 1) then
        content = content .. [[
                            <b><img src="images/ok.png"/> Saved new device with serial ]]..d.serial..[[</b><br><br>
]]
    else
        content = content .. [[
                            <b><img src="images/ok.png"/> Changes saved.</b><br><br>
]]
    end
end
content = content .. [[
                            <input type="hidden" name="bus" value="]]..bus..[["/>
                            <input type="hidden" name="file" value="]]..filename..[["/>
                            <input type="button" name="backButton" value="Back to bus configuration" onclick="window.location.assign('rsm_bus_config.lua?bus=]]..bus..[[');"/>
                     ]]

if (mode == 'new') then
    content = content .. [[<input type="submit" name="saveButton" value="Create Device"]]..buttonControl..[[ onclick="doValidate = 1;"/>]]
    content = content .. [[
                            <input type="submit" name="deleteButton" value="Delete Device"]]..buttonControl..[[ onclick="doValidate = 1;"/>
                            ]]
end

if (mode == "edit") then
    content = content .. [[
                            <input type="submit" name="deleteButton" value="Delete Device"]]..buttonControl..[[ onclick="return confirm('Are you sure you want to delete this device?');"/>
]]
end
content = content .. [[
                        </form>
                    </div>

]]

if (mode == "edit") then
    cfg = cfg:gsub("<","&lt;")
    cfg = cfg:gsub(">","&gt;")
    content = content .. [[
                    <script>
                        function toggleVis(target)
                        {
                            if (target.style.display == "none")
                            {
                                target.style.display = "inline-block";
                            }
                            else
                            {
                                target.style.display = "none";
                            }
                            return false;
                        }
                    </script>
                    <br><img src="images/magnify.png"/> <a href="javascript:void(0)" onclick="toggleVis(document.getElementById('filecfg'));">View ]]..ck200Path..[[/]]..filename..[[</a></a><br>

                    <div id="filecfg" style="display: none;">
                        <pre class="formLayoutfull">
]]..cfg..[[
                        </pre>
                    </div>
]]
end


print(header..content..footer)
