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

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

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

camera_config_file = command.ex([[cat ]]..rsm_conf.camera_xml_path) or ""
templatesFiles = {}
if (camera_config_file ~= "") then
    camera_device_path = camera_config_file:match([[<path%s+name=%"devices%"%s->(.-)</path>]]) or ""
    templatesPath = camera_config_file:match([[<path%s+name=%"templates%"%s->(.-)</path>]]) or ""
    if (templatesPath ~= "") then
        templatesFiles = command.getFilesInTable(templatesPath)
    end

    camera_profile_path = camera_config_file:match([[<path%s+name=%"profiles%"%s->(.-)</path>]]) or ""
    if (camera_profile_path ~= "") then
        camera_profile_file = command.ex([[cat ]]..camera_profile_path) or ""
    end
end

if (cgi.post.deleteButton == "Delete Device") and (userLevel ~= 1) then
    file = cgi.post.file or ""
    file = file:gsub("[^%w%.]+","")
    existingCfg = command.ex([[cat ]]..camera_device_path..[[/]]..file)
    newSerial = existingCfg:match([[<serial>%s-(.-)%s-</serial>]])

    command.ex(rsm_conf.cdd_down)
    command.ex(rsm_conf.wtr_down)
    command.ex(rsm_conf.blackwall_down)

    for setting in camera_profile_file:gmatch("(<camera>(.-)</camera>)") do
        local serial = setting:match("<serial>(.-)</serial>")
        if (serial == newSerial) then
            camera_profile_file = camera_profile_file:gsub(setting, "")
            command.writefile(camera_profile_path, camera_profile_file)
        end 
    end

    command.ex([[rm ]]..camera_device_path..[[/]]..file)
    command.ex([[rm ]].."/etc/blackwall/cameras/".. file)

    command.ex(rsm_conf.cdd_up)
    command.ex(rsm_conf.wtr_up)
    command.ex(rsm_conf.blackwall_up)
    label = cgi.post.label or "unknown"
    -- bus = cgi.post.bus or "unknown"
    -- Stop here
    content = [[
                    <div id="info">
                        <center><h1>Edit Camera Device</h1></center>
                    </div>                  
                    <div id="info">
                        <center>
                            <h2><img src="images/ok.png"/>Camera Device Deleted</h2>
                            Device with filename "]]..file..[[" has been removed.<br><br>
                            <a href="rsm_bus_config.lua">Back to cameras</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 ""
    newFile = newFile:gsub("[^%w%.]+","")
    if (newFile == "") then
        newSerial = rsm_serials.generateNewSerial()
        newFile = newSerial..".xml"
        createdNew = 1
    else
        createdNew = 0
        existingCfg = command.ex([[cat ]]..camera_device_path..[[/]]..newFile)
        newSerial = existingCfg:match([[<serial>%s-(.-)%s-</serial>]])
        if (newSerial == nil) then
            -- Bail on error
            content = [[
                    <div id="info">
                        <center><h1>Edit Camera 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
    newLabel = cgi.post.label or "unknown"
    newTemplate = cgi.post.template or "unknown"
    newIP = cgi.post.ip or "192.168.1.2"
    newUserName = cgi.post.user_name or "unknown"
    newPassword = cgi.post.user_password or "unknown"
    new_external_rtsp_port = cgi.post.external_rtsp_port or "unknown"
    rtsp_server_port = cgi.post.rtsp_server_port or "unknown"

    newXML = [[
<!-- ]]..camera_device_path..[[/]]..newFile..[[ generated by webconfig -->
<device>
    <label>]]..newLabel..[[</label>
    <serial>]]..newSerial..[[</serial>
    <template>]]..newTemplate..[[</template>
    <ip>]]..newIP..[[</ip>
    <external_rtsp_port>]]..new_external_rtsp_port..[[</external_rtsp_port>
    <rtsp_server_port>]]..rtsp_server_port..[[</rtsp_server_port>
    <user_name>]]..newUserName..[[</user_name>
    <user_password>]]..newPassword..[[</user_password>
</device>
<!-- end of file -->
]]

    local rtsp_server_port_start = string.format("%i", rtsp_server_port + 101) ;
    local rtsp_server_port_end = string.format("%i", rtsp_server_port + 701) ;

    newConf = ""
    newConf = newConf .. "ppp0" .. "\t" .. "tcp" .. "\t" .. new_external_rtsp_port .. "\t" .. newIP .. "\t" .. "554" .. "\n"
    newConf = newConf .. "ppp1" .. "\t" .. "tcp" .. "\t" .. new_external_rtsp_port .. "\t" .. newIP .. "\t" .. "554" .. "\n"
    -- newConf = newConf .. "ppp0" .. "\t" .. "udp" .. "\t" .. rtsp_server_port_start .. ":" .. rtsp_server_port_end .. "\t" .. newIP .. "\t" .. rtsp_server_port_start .. ":" .. rtsp_server_port_end .. "\n"
    -- newConf = newConf .. "ppp1" .. "\t" .. "udp" .. "\t" .. rtsp_server_port_start .. ":" .. rtsp_server_port_end  .. "\t" .. newIP .. "\t" .. rtsp_server_port_start .. ":" .. rtsp_server_port_end .. "\n"
    command.writefile("/etc/blackwall/cameras/"..newSerial..".xml", newConf)

    command.ex(rsm_conf.cdd_down)
    command.ex(rsm_conf.wtr_down)
    command.ex(rsm_conf.blackwall_down)
    command.writefile(camera_device_path..[[/]]..newFile, newXML)

    if (createdNew == 1) then
        new_profile_entry = 
[[  <camera>
        <serial>]]..newSerial..[[</serial>
        <triggers></triggers>
        <actions></actions>
        <auto_timeoff>]].."20"..[[</auto_timeoff>
  </camera>
  </cameras>

]]
        camera_profile_file = camera_profile_file:gsub("</cameras>", new_profile_entry)
        command.writefile(camera_profile_path, camera_profile_file)
    end

    command.ex(rsm_conf.cdd_up)
    command.ex(rsm_conf.wtr_up)
    command.ex(rsm_conf.blackwall_up)
    filename = newFile
    saved = 1
    mode = "edit"
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 ""

if (mode == "edit") then
    
    cfg = command.ex([[cat ]]..camera_device_path..[[/]]..filename) or ""
    if (cfg:match("<device>(.+)</device>") == nil) then
        -- bail on error
        content = [[
                    <div id="info">
                        <center><h1>Edit Camera 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 camera 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.label = cfg:match([[<label>%s-(.-)%s-</label>]]) or "unknown"
        d.serial = cfg:match([[<serial>%s-(.-)%s-</serial>]]) or "unknown"
        d.template = cfg:match([[<template>%s-(.-)%s-</template>]]) or "unknown"
        d.ip = cfg:match([[<ip>%s-(.-)%s-</ip>]])
        d.user_name = cfg:match([[<user_name>%s-(.-)%s-</user_name>]])
        d.user_password = cfg:match([[<user_password>%s-(.-)%s-</user_password>]])
        d.external_rtsp_port = cfg:match([[<external_rtsp_port>%s-(.-)%s-</external_rtsp_port>]])
        d.rtsp_server_port = cfg:match([[<rtsp_server_port>%s-(.-)%s-</rtsp_server_port>]])

    end
else
    d = {}
    d.label = ""
    d.serial = "(unassigned)"
    d.template = ""
    d.config = rsm_conf.serialconfig_path
    d.ip = ""
    d.external_rtsp_port = ""
    d.rtsp_server_port = ""
    d.user_name = ""
    d.user_password = ""
    
end

templatesOptions = [[
                                        <option disabled ]] if (mode == "new") then templatesOptions = templatesOptions..[[selected]] end templatesOptions = templatesOptions..[[>Select a template</option>
]]

foundTemplate = 0
if (#(templatesFiles) > 0) then
    for i,f in pairs(templatesFiles) do
        templatesOptions = templatesOptions..[[
                                        <option value="]]..f..[["]] if f == d.template then templatesOptions = templatesOptions .. [[ selected ]] foundTemplate = 1 end templatesOptions = templatesOptions..[[>]]..f..[[</option>
]]            
    end
else
        templatesOptions = [[
                                        <option disabled selected>No templates found</option>
]]
    foundTemplate = 1 -- Yeah this looks like it doesn't make sense, but it does
end
if (foundTemplate == 0) and (mode ~= "new") then
    templatesOptions = templatesOptions .. [[
                                        <option value="]]..d.template..[[" selected title="Template not found!">Template not found (]]..d.template..[[)</template>
]]        
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 Camera 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 Camera Device</h1></center>
                        </div>
                    </div>
                    <h3>Editing device "]]..d.label..[[" with filename "]]..filename..[[" :</h3>
]]    
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 errors = 0;

                            var label_element = document.getElementById("label");
                            var warning;                           
                            if (label_element.value == "")
                            {
                                errors++;
                            }
                            
                            var template = document.getElementById("template");
                            var warning = document.getElementById("templatewarning");                            
                            if (template.value == "Select a template")
                            {
                                if (!warning)
                                {
                                    warning = document.createElement("span");
                                    warning.id = "templatewarning";
                                    warning.innerHTML = " <img src='images/warning.png' alt='Choose a valid template' title='Choose a valid template'/>";
                                    template.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_cam_edit.lua" method="post" onsubmit="return validateForm(this);">
                        <div class="formLayoutfull">
                            <table class="onetwo">
                                <tr>
                                    <td style="padding: 5px;" width="50%">
                                        <b>Device Label:</b>
                                    </td>
                                    <td style="padding: 5px;" width="50%">
                                        <input type="text" name="label" value="]]..d.label..[["]]..inputControl..[[ id="label"/>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="padding: 5px;">
                                        <b>Device Serial:</b>
                                    </td>
                                    <td style="padding: 5px;">]]..d.serial..[[</td>
                                </tr>
                                <tr>
                                    <td style="padding: 5px;">
                                        <b>Template File:</b>
                                    </td>
                                    <td style="padding: 5px;">
                                        <select name="template"]]..buttonControl..[[ id="template">
]]
content = content .. templatesOptions
content = content .. [[
                                        </select>
                                    </td>
                                </tr>
                                <tr>
                                <td style="padding: 5px;" width="50%">
                                    <b>IP Address:</b>
                                </td>
                                <td style="padding: 5px;" width="50%">
                                    <input type="text" name="ip" value="]]..d.ip..[["]]..inputControl..[[ id="ip"/>
                                </td>
                                </tr>
                                <tr>
                                <td style="padding: 5px;" width="50%">
                                    <b>External RTSP port:</b>
                                </td>
                                <td style="padding: 5px;" width="50%">
                                    <input type="text" name="external_rtsp_port" value="]]..d.external_rtsp_port..[["]]..inputControl..[[ id="external_rtsp_port"/>
                                </td>
                                </tr>
                                <tr>
                                <td style="padding: 5px;" width="50%">
                                    <b>RTSP server port:</b>
                                </td>
                                <td style="padding: 5px;" width="50%">
                                    <input type="text" name="rtsp_server_port" value="]]..d.rtsp_server_port..[["]]..inputControl..[[ id="rtsp_server_port"/>
                                </td>
                                </tr>
                                <tr>
                                <td style="padding: 5px;" width="50%">
                                    <b>Username:</b>
                                </td>
                                <td style="padding: 5px;" width="50%">
                                    <input type="text" name="user_name" value="]]..d.user_name..[["]]..inputControl..[[ id="user_name"/>
                                </td>
                                </tr>
                                <tr>
                                <td style="padding: 5px;" width="50%">
                                    <b>User Password:</b>
                                </td>
                                <td style="padding: 5px;" width="50%">
                                    <input type="text" name="user_password" value="]]..d.user_password..[["]]..inputControl..[[ id="user_password"/>
                                </td>
                                </tr>
                            </table>
                            <br>
                            <hr>
                            <br>
]]
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
-- <input type="hidden" name="config" value="]]..d.config..[["/>
-- <input type="hidden" name="bus" value="]]..bus..[["/>
content = content .. [[
                            <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');"/>
                            <input type="submit" name="saveButton" value="Save and Apply"]]..buttonControl..[[ onclick="doValidate = 1;"/>
]]
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 ]]..camera_device_path..[[/]]..filename..[[</a></a><br>
        
                    <div id="filecfg" style="display: none;">
                        <pre class="formLayoutfull">
]]..cfg..[[
                        </pre>
                    </div>    
]]
end


print(header..content..footer)
