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"
    scriptControl = "//"
else
    buttonControl = ""
    inputControl = ""
    scriptControl = ""
end

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

bddPath = rsm_conf.bdd_device_path

if (cgi.post.deleteButton == "Delete Device") and (userLevel ~= 1) then
    file = cgi.post.file or ""
    file = file:gsub("[^%w%.]+","")
    command.ex(rsm_conf.bdd_down)
    command.ex([[rm ]]..bddPath..[[/]]..file)
    command.ex(rsm_conf.bdd_up)
    label = cgi.post.label or "unknown"
    -- bus = cgi.post.bus or "unknown"
    -- Stop here
    content = [[
                    <div id="info">
                        <center><h1>Edit RSM VOIP 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">Back to bus configuration</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 ]]..bddPath..[[/]]..newFile)
        newSerial = existingCfg:match([[<serial>%s-(.-)%s-</serial>]])
        if (newSerial == nil) then
            -- Bail on error
            content = [[
                    <div id="info">
                        <center><h1>Edit RSM VOIP 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"
    newVolume_level = cgi.post.volume_level
    newXML = [[
<!-- ]]..bddPath..[[/]]..newFile..[[ generated by webconfig -->
<bdd>
    <label>]]..newLabel..[[</label>
    <serial>]]..newSerial..[[</serial>
    <volume_level>]]..newVolume_level..[[</volume_level>

    <contacts>
]]

    new_account_username = cgi.post.account_username or "unknown"
    new_account_password = cgi.post.account_password or "unknown"
    new_account_domain = cgi.post.account_domain or "unknown"
    new_sip_account_string = "<sip:" .. new_account_username .. ":" .. new_account_password .. "@" .. new_account_domain .. ">;answermode=auto"

   
    for count = 1,10 do
        new_contact_label = cgi.post["label"..count]
        new_contact_name = cgi.post["contact_name"..count]
        new_contact_domain = cgi.post["contact_domain"..count]

        if (new_contact_label ~= nil) then
            -- command.log("Adding new contact: "..cgi.post["label"..count])

            if (new_contact_label ~= "") and (new_contact_name~= "") and (new_contact_domain ~= "") then

                newXML = newXML ..
[[      <contact>
            <address>]]..new_contact_name .. "@" .. new_contact_domain .. [[</address>
            <label>]] .. new_contact_label .. [[</label>
        </contact>
]]
            end
        end
    end

    newXML = newXML .. 
[[      
    </contacts>
</bdd>
<!-- end of file -->
]]
    
    command.ex(rsm_conf.bdd_down)
    command.writefile(bddPath..[[/]]..newFile, newXML)
    command.writefile("/etc/baresip/accounts", new_sip_account_string)
    
    if (newVolume_level == "low") then
        command.ex("amixer set 'Speaker Analog' 25%")
    elseif (newVolume_level == "medium") then
        command.ex("amixer set 'Speaker Analog' 50%")
    elseif (newVolume_level == "high") then
        command.ex("amixer set 'Speaker Analog' 85%")
    elseif (newVolume_level == "level 11") then
        command.ex("amixer set 'Speaker Analog' 100%")
    end


    command.ex(rsm_conf.bdd_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 ""
voip_contacts = {}

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

if (mode == "edit") then
    cfg = command.ex([[cat ]]..bddPath..[[/]]..filename) or "" 
    cfg_account = command.ex([[cat /etc/baresip/accounts]]) or ""
    if (cfg:match("<bdd>(.+)</bdd>") == nil) then
        -- bail on error
        content = [[
                    <div id="info">
                        <center><h1>Edit RSM VOIP 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 RSM VOIP 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.volume_level = cfg:match([[<volume_level>%s-(.-)%s-</volume_level>]]) or "unknown"



for name,b in cfg:gmatch([[<contact>%s-(.-)%s-</contact>]]) do
        local label = name:match([[<label>%s-(.-)%s-</label>]]) or "unknown"
        local contact_name =name:match([[<address>%s-(.-)%s-@]]) or "unknown"
        local contact_address =name:match([[@%s-(.-)%s-</address>]]) or "unknown"

        -- command.log("contact_name: " ..contact_name )
        -- command.log("contact_address: " ..contact_address )
 
    if (label ~= nil) and (contact_name ~= nil)then
        voip_contact = {}
        voip_contact.label = label
        voip_contact.contact_name = contact_name
        voip_contact.contact_domain = contact_address
        table.insert(voip_contacts, voip_contact)
    end
end

        d.account_username =  cfg_account:match([[<sip:%s-(.-)%s-:]]) or "unknown"
        d.account_password =  cfg_account:match([[<sip:]]..d.account_username..[[:%s-(.-)%s-@]]) or "unknown"
        d.account_domain =  cfg_account:match([[<sip:]]..d.account_username..[[:]]..d.account_password..[[@%s-(.-)%s->]]) or "unknown"
    end
else
    d = {}
    d.label = ""
    d.serial = "(unassigned)"
    d.volume_level = ""
    
    d.account_username =  ""
    d.account_password =  ""
    d.account_domain =  ""

end

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

defined_volume_levels = {"low", "medium", "high", "level 11"}

    for i,f in pairs(defined_volume_levels) do
        volume_options = volume_options..[[
                                        <option value="]]..f..[["]] if f == d.volume_level then volume_options = volume_options .. [[ selected ]] end volume_options = volume_options..[[>]]..f..[[</option>
]]            
    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 RSM VOIP 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 RSM VOIP 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++;
                            }
                                                        
                            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;
                            }
                        }

                        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 == "contacts")
                                {
                                  for (loop = 0; loop < all_inputs.length; loop+=3)
                                  {
                                      all_inputs[loop].name = "label"+((loop/3)+1);
                                      all_inputs[loop+1].name = "contact_name"+((loop/3)+1);
                                      all_inputs[loop+2].name = "contact_domain"+((loop/3)+1);
                                  }
                                }
                            }

                        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("input"); //Get all the input fields in the given area.
                                count = all_inputs.length/3;
                                console.log("count: " + count)
                                if(count+1 > limit && limit > 0)
                                    return;
                                if(document.createElement)
                                {
                                    var li = document.createElement("li");  
                                    if (field == "contacts")
                                    {
                                     li.innerHTML = 
                                        "<input type=\"text\" name=\"label"+(count+1)+"\" value=\"\" style=\"width: 150px;\" placeholder=\"Label\"/> "
                                        +"<input type=\"text\" name=\"contact_name"+(count+1)+"\" value=\"\" style=\"width: 100px;\" placeholder=\"Contact Name\"/> "
                                        +"<input type=\"text\" name=\"contact_domain"+(count+1)+"\" value=\"\" style=\"width: 160px;\" placeholder=\"Contact Domain\"/> "
                                        +"<a style=\"cursor:pointer;color:blue;\" onclick=\"removeField(this, '"+field+"');\"> <img src=\"images/trash.png\" alt=\"Delete\" title=\"Delete\"/></a>";
                                    }
                                    field_area.appendChild(li);
                                }
                            }
                    
                    </script>
                    
                    <form action="rsm_voip_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;" width="50%">
                                        <b>Account Username:</b>
                                    </td>
                                    <td style="padding: 5px;" width="50%">
                                        <input type="text" name="account_username" value="]]..d.account_username..[["]]..inputControl..[[ id="account_username"/>
                                    </td>
                                </tr>
                                <tr>
                                    <td style="padding: 5px;" width="50%">
                                        <b>Account Password:</b>
                                    </td>
                                    <td style="padding: 5px;" width="50%">
                                        <input type="text" name="account_password" value="]]..d.account_password..[["]]..inputControl..[[ id="account_password"/>
                                    </td>
                                </tr>
                                <tr>
                                <td style="padding: 5px;" width="50%">
                                    <b>Account Domain:</b>
                                </td>
                                <td style="padding: 5px;" width="50%">
                                    <input type="text" name="account_domain" value="]]..d.account_domain..[["]]..inputControl..[[ id="account_domain"/>
                                </td>

                                <tr>
                                <td style="padding: 5px;">
                                    <b>Volume Level:</b>
                                </td>
                                <td style="padding: 5px;">
                                    <select name="volume_level"]]..buttonControl..[[ id="volume_level">
]]
content = content .. volume_options
content = content .. [[
                                    </select>
                                </td>
                            </tr>
                            </table>
                            <br>
                             ]] 

                             content = content .. [[
        
                    <class="formLayoutfull">
                        <form action="rsm_voip_edit.lua" method="post" onsubmit="return validateForm(this);">
                        <h3>List of contacts</h3>
                        <div id="conatactsDiv">
                     
                            <ol id="contacts_list">
]]





-- command.log("#(voip_contacts)  " .. #(voip_contacts))

if (#(voip_contacts) > 0) then
    for i = 1, #(voip_contacts)  do
        if (i > 0) then
            content = content .. [[
                            <li>
                          
                                <input type="text" name="label]]..i..[[" value="]]..voip_contacts[i].label..[[" style="width: 150px;" placeholder="Label"]]..inputControl..[[/>
                                <input type="text" name="contact_name]]..i..[[" value="]]..voip_contacts[i].contact_name..[[" style="width: 100px;" placeholder="Contact Name"]]..inputControl..[[/>
                                <input type="text" name="contact_domain]]..i..[[" value="]]..voip_contacts[i].contact_domain..[[" style="width: 160px;" placeholder="Contact Domain"]]..inputControl..[[/>
                                <a style="cursor:pointer;color:blue;" onclick="]]..scriptControl..[[removeField(this, 'contacts');"> <img src="images/trash.png" alt="Delete" title="Delete"/></a>
                          </li>
]]
        end
    end
end




content = content .. [[
    </ol>
   </div>
                      
                        <input type="button" value="Add Contact" onclick="addField('contacts',4);"]]..buttonControl..[[/>
                

                        <br><br><hr><br>
                        </form>
]]


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="submit" name="saveButton" value="Save and Apply"]]..buttonControl..[[ onclick="doValidate = 1;"/>
                        </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 ]]..bddPath..[[/]]..filename..[[</a></a><br>
        
                    <div id="filecfg" style="display: none;">
                        <pre class="formLayoutfull">
]]..cfg..[[
                        </pre>
                    </div>    
]]
end

      


print(header..content..footer)
