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

local scan_complete = 0
local scan_err = nil
local scan = {}
scan.host = cgi.post.host or ""
scan.service = cgi.post.service or "502"
scan.slaves = 15

-- Create scanning function so that we can call it and modify scan state above.
local function perform_scan()
    local Scanner = require('luamods.modbus_scan.Scanner')
    local DeviceCreator = require('luamods.modbus_scan.DeviceCreator')
    local file = require('pl.file')

    local scanner = Scanner('/etc/rsm/mdd/templates', scan.host .. ':' .. scan.service)
    local device_creator = DeviceCreator('/etc/rsm/mdd/device_template.xml', '/etc/rsm/mdd/devices')

    -- Read all available templates.
    local err = scanner:prepare()
    if err then
        scanner:close()
        return err
    end

    -- Prepare device creator with template.
    local err = device_creator:prepare()
    if err then
        scanner:close()
        return err
    end

    -- Scan endpoint for all slaves.
    local scanned_slaves = scanner:scan_slaves(scan.slaves)

    scanner:close()

    -- With the scanned slaves, create required slave devices.
    local err = device_creator:create_slave_devices(scanned_slaves, scanner:get_host(), scanner:get_port())
    if err then
        scanner:close()
        return err
    end

    -- Create a lock file to prevent restarts.
    -- This allows a user an opportunity to edit devices before they are created.
    file.write(rsm_conf.mdd_restart_lock, '')

    return nil
end

if (cgi.post.scanButton == "Start Scan") and (userLevel ~= 1) then
    scan_complete = 1
    scan_err = perform_scan()
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>Scan a Modbus Device</h1></center>
        </div>
    </div>
]]

if (userLevel == 1) then
    content = content .. [[
    <center><b>Note:</b> Scanning Modbus devices 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 loop;
                            var errors = 0;
                            for (loop = 0; loop < 2; loop++)
                            {
                                var warning = document.getElementById("warning"+loop);
                                if (inputs[loop].value == "")
                                {
                                    if (!warning)
                                    {
                                        warning = document.createElement("span");
                                        warning.id = "warning"+loop;
                                        warning.innerHTML = " <img src='images/warning.png' alt='Cannot be blank' title='Cannot be blank'/>";
                                        inputs[loop].parentNode.appendChild(warning);
                                    }
                                    errors++;
                                }
                                else
                                {
                                    if (warning)
                                    {
                                        warning.parentNode.removeChild(warning);
                                    }
                                }
                            }
                            
                            if (errors)
                            {
                                alert("Not all fields have been filled in.\nPlease enter/select valid values for the indicated fields.");
                                return false;
                            }
                            else
                            {
                                form.setAttribute('submitted','true');
                                return true;
                            }
                        }
                    
                    </script>    

                    <form action="rsm_modbus_scan.lua" method="post" onsubmit="return validateForm(this);">
                        <div class="formLayoutfull">
                            <table class="onetwo">
                                <tr>
                                    <td style="padding: 5px;" width="30%">
                                        <b>TCP Host:</b>
                                    </td>
                                    <td style="padding: 5px;" width="70%">
                                        <input type="text" name="host" value="]]..scan.host..[["]]..inputControl..[[/>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="padding: 5px;">
                                        <b>Service/port:</b>
                                    </td>
                                    <td style="padding: 5px;" width="70%">
                                        <input type="text" name="service" value="]]..scan.service..[["]]..inputControl..[[/>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="padding: 5px;">
                                        <b>Try slaves:</b>
                                    </td>
                                    <td style="padding: 5px;">
                                        <input type="text" name="slaves" value="]]..scan.slaves..[["]]..inputControl..[[/>
                                    </td>
                                </tr>
                            </table>
                            <br>
                            <hr>
                            <br>
]]

if (scan_complete == 1) then



if scan_err then
    content = content .. [[
        <b><img src="images/warning.png"/> ]] .. scan_err .. [[ </b><br><br>
    ]]
else
    content = content .. [[
        <b><img src="images/ok.png"/> Scan Complete. </b>
        You can now edit each device in the bus config. Don't forget to unlock and save the
        Modbus TCP devices in the bus configuration page.
        <br><br>
    ]]
end

end

content = content .. [[
    <input type="button" name="backButton" value="Back to Bus Configuration" onclick="window.location.assign('rsm_bus_config.lua');"/>
    <input type="submit" name="scanButton" value="Start Scan"]]..buttonControl..[[ onclick="doValidate = 1;"/>
]]

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

print(header..content..footer)
