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 ""
ckdConfig = command.ex([[cat ]]..rsm_conf.ckdd_conf_path) or ""
if (ckdConfig ~= "") then
    ckdPath = ckdConfig:match([[ckdd.device.dir=(.*)%$]]) or "/etc/rsm/ckdd/devices"
    log("path read: " .. ckdPath)
    if (ckdPath ~= "") then
        ckdFiles = command.getFilesInTable(ckdPath)
    end
end

if (cgi.post.deleteButton == "Delete Device") and (userLevel ~= 1) then
    file = cgi.post.file or ""
    file = file:gsub("[^%w%.]+","")
    command.ex([[rm ]]..ckdPath..[[/]]..file)
    label = cgi.post.label or "unknown"
    bus = cgi.post.bus or "unknown"

    command.ex(rsm_conf.ckdd_restart)

    content = [[
                    <div id="info">
                        <center><h1>Edit CKD 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_ckd_config.lua?bus=]]..bus..[[">Back to CKD</a>
                        </center>
                    </div>
]]
    print(header..content..footer)
    os.exit()
end

if (cgi.post.saveButton == "Save and Apply") and (userLevel ~= 1) then
    newFile = cgi.post.file or ""
    -- NOTE(Trevor): For now we assumme this only happens on 'Create'

    numSlaves = cgi.post.numSlaves or "3"
    log("Number of slaves: " .. numSlaves)
    --newFile = newFile:gsub("[^%w%.]+","")
    local slaves = {}
    if (newFile == "") then
        -- Generate serial for the master
        newMaster = rsm_serials.generateNewSerial()
        -- Generate serial for the number for slaves
        for i = 1, tonumber(numSlaves) do
            table.insert(slaves, {index=i, serial=rsm_serials.generateNewSerial()})
        end
        
        newFile = newMaster..".xml"
        createdNew = 1
    else
        createdNew = 0
        existingCfg = command.ex([[cat ]]..ckdPath..[[/]]..newFile)
        newMaster = existingCfg:match([[<master>%s-(.-)%s-</master>]])
        newSlave = existingCfg:match([[<slave>%s-(.-)%s-</slave>]])
        if (newSerial == nil) then
            -- Bail on error
            content = [[
                    <div id="info">
                        <center><h1>Edit CKD Device</h1></center>
                    </div>
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"/> Filename / serial mismatch</h2>
                            The serial number of the device does not match the one in the file.<br>
                            <a href="rsm_bus_config.lua">Back to Bus Configuration</a>
                        </center>
                    </div>
]]
            print(header..content..footer)
            os.exit()
        end
    end
    
    newPort = cgi.post.bus or "unknown"
    newOwner = "ckdd"
    newXML = [[
<!-- ]]..ckdPath..[[/]]..newFile..[[ generated by webconfig -->
<CK100>
        <port>]]..newPort..[[</port>
        <master>]]..newMaster..[[</master>
        <numSlaves>]]..numSlaves..[[</numSlaves>
        ]].."\n"

          for i,slave in ipairs(slaves) do
              newXML = newXML..[[<slave]]..slave.index..[[>]]..slave.serial..[[</slave]]..slave.index..[[>]].."\n"
          end

          newXML = newXML..[[

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

else
    filename = cgi.get.file or ""
    if (filename == "") then
        mode = "new"
    else
        --filename = filename:gsub("[^%w%.]+","")
        mode = "edit"
    end
    

end

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


--b, bCfg = serialConfig:match([[<port%s+device=%"(]]..bus..[[)%"%s->(.-)</port>]])
--if (b == bus) and (bCfg ~= nil) then
--    if bCfg:match("<owner>%s-ckdd%s-</owner>") == nil then
--        mismatch = 1
--    else
--       mismatch = 0
--    end
--else
--    mismatch = 1
--end
if (mode == "edit") then

    cfg = command.ex([[cat ]]..ckdPath..[[/]]..filename) or ""
    if (cfg:match("<CK100>(.+)</CK100>") == nil) then
        -- bail on error
        content = [[
                    <div id="info">
                        <center><h1>Edit CKD 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 CKD 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.master = cfg:match([[<master>%s-(.-)%s-</master>]]) 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 CKD 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 = "ckdd"
      local temp_slave = cfg:match([[<slaves>%s-(.-)%s-</slaves>]]) or ""
        d.slaves = {}

        -- counter = 0 

      for slave_match in temp_slave:gmatch("<slave%s*(.-)%s-</slave>") do
        local slave = {}
        -- counter = counter + 1 
        slave.label = slave_match:match([[%"(.-)%"%s*>(.*)]])
        table.insert(d.slaves, slave)
        -- command.log("\n\n\nFound another slave")
      end
      d.numSlaves = cfg:match([[<numSlaves>%s-(.-)%s-</numSlaves>]]) or "0" 

    end
else
    d = {}
    d.master = "(unassigned)"
    d.port = bus
    d.owner = "ckdd"
    d.slave = "(unassigned)"
    d.numSlaves = 0
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>Add New CKD Device</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>Edit CKD Device</h1></center>
                        </div>
                    </div>
                    <h3>Editing device with 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 CKD 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>
                        function removeField(node,field)
                        {
                            node.parentNode.parentNode.removeChild(node.parentNode);
                            var field_area = document.getElementById(field+"_list");
                            var all_inputs = field_area.getElementsByTagName("input"); //Get all the input fields in the given area.

                            var loop;

                            if (field == "slave")
                            {

                              for (loop = 0; loop < all_inputs.length; loop+=1)
                              {

                                  all_inputs[loop].name = "slave"+(loop+1);
                              }
                              for (loop = 0; loop < all_selects.length; loop+=1)
                              {
                                  all_selects[loop].name = "input"+(loop+1);
                              }

                            }
                        }



                        //Add more fields dynamically.
                        function addField(field, limit)
                        {
                            if (!document.getElementById) return; //Prevent older browsers from getting any further.
                            var field_area = document.getElementById(field+"_list");
                            var all_inputs = field_area.getElementsByTagName("select"); //Get all the input fields in the given area.
                            var count = all_inputs.length;
                            if (field == "slave")
                            {
                               count = count;
                            }
                            if(count+1 > limit && limit > 0) return;

                            if(document.createElement)
                            { //W3C Dom method.
                                if (field == "slave")
                                {
                                    var li = document.createElement("li");
                                    li.innerHTML ="<input name=\"slave"+(count+2)+"\" style=\"width:150px;\"/>"
                                    +"<a style=\"cursor:pointer;color:blue;\" onclick=\"removeField(this, '"+field+"');\"><img src=\"images/trash.png\" alt=\"Delete\" title=\"Delete\"/></a>";

                                    field_area.appendChild(li);

                                }
                            }
                            else
                            {       //Older Method
                            }

                        }
                        //validate
                                                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>

]]

-- NOTE(Trevor): This is a hack need to clean up a bit
if (mode == 'edit') then
content = content .. [[

                    <div class="formLayoutfull">
                        <form action="rsm_ckd_edit.lua" method="post" onsubmit="return validateForm(this);">
                            <h3>Master serial: ]] .. d.master .. [[</h3>
                            <h4>Number of slaves: ]] .. d.numSlaves .. [[</h4>
                            <ol id="slave_list">
                    ]]
else
content = content .. [[

                    <div class="formLayoutfull">
                        <form action="rsm_ckd_edit.lua" method="post" onsubmit="return validateForm(this);">
                            <h3>Create new CK100 device</h3>
                            <label>Number of slaves</label>
                            <select name="numSlaves" id="numSlaves">
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3" selected>3</option>
                                <option value="4">4</option>
                                <option value="5">5</option>
                                <option value="6">6</option>
                            </select>
                            <ol id="slave_list">
                    ]]
end



--if (#(d.slaves) > 0) then
      --  for i = 1, #(d.slaves)  do
        --    if (i > 0) then

 -- content=content..[[             <li><input name="slave]]..[[" style="width:150px;" value="]].. [["/>
--]]

--  end
 -- end
--  end
-- Add button to be used later
-- <input type="button" value="Add slave" onclick="addField('slave', 6);"]]..buttonControl..[[/>

    content = content .. [[
                            </ol>

]]
if (saved == 1) then
    if (createdNew == 1) then
        content = content .. [[
                            <b><img src="images/ok.png"/> Saved new device with serial ]]..d.master..[[</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 CKD" onclick="window.location.assign('rsm_ckd_config.lua?bus=]]..bus..[[');"/>
                     ]]
-- Add 'Save and Apply' on new only
if (mode == 'new') then
    content = content .. [[<input type="submit" name="saveButton" value="Save and Apply"]]..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 ]]..ckdPath..[[/]]..filename..[[</a></a><br>

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


print(header..content..footer)
