-- platform_config.lua
--
-- Implements the web module to configure the communication up to the platform server configuration file.
--
require("luamods/layout")
require("luamods/command")
require("config/remote_access_conf")
local PropertyConfig = require("luamods/property_config")

--
-- Figure out user permission stuffies.
--
userLevel = db.getPriv(layout.username) or 1

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

-- Read config for bibun daemon into config management.
local properties = PropertyConfig.new(remote_access_conf.bibunconfig_path)

if properties then
  -- Schedule restart of the bibun daemon for any changes to the config file.
  local function restartBibunDaemon()
    command.log('Restarting bibund, config was changed.')
    command.ex(remote_access_conf.bibund_ram_restart)
  end
  properties:registerOnChangeAction(restartBibunDaemon)

  if (cgi.post["submitPlatformButton"] ~= nil) and (userLevel ~= 1) then
    local new_bibun_host = cgi.post.bibun_host_input
    local new_bibun_port = cgi.post.bibun_port_input
    local new_forwarder_remote = "tcp://"..new_bibun_host..":"..new_bibun_port

    -- Apply changes to the properties table from cgi post.
    properties:applyIfDifferent({"bibun", "forwarder", "remote"}, new_forwarder_remote)
    properties:applyIfDifferent({"bibun", "inbox_interval"}, cgi.post.bibun_inbox_interval_input)

    -- Write changes to config file and restart services if anything was updated.
    properties:saveIfChanged()
  end

  -- The following entries should have some value.
  local forwarder_remote = properties:get({"bibun", "forwarder", "remote"}) or ""
  bibun_inbox_interval = properties:get({"bibun", "inbox_interval"}) or "2"

  -- Host and port need to be inferred from the forwarder remote...which is a uri.
  bibun_host = string.match(forwarder_remote, "tcp://([^:]+):")
  bibun_port = string.match(forwarder_remote, "tcp://[^:]+:(%d+)")
end

function generateContentWarning(headerText, messageText)
  return [[
    <div id="info">
      <center>
        <h2><img src="images/warning.png"/> ]]..headerText..[[</h2>
        ]]..messageText..[[
      </center>
    </div>
  ]]
end

--
-- Generate content for the final webpage.
--
function generateServerConfigContent()
  -- Heading
  content = [[
    <div id="info">
      <div style="background-size:32px; background-repeat:no-repeat; background-position: 20px center;">
          <center><h1>Platform Server configuration</h1></center>
      </div>
    </div>
  ]]

  -- Check if the properties could be read from the config file.
  if not properties then
    content = content..generateContentWarning("Cannot read config file",
      [[The server communication configuration file "]]..remote_access_conf.bibunconfig_path..[[" is missing or unreadable.]]
    )

    return content -- Return early, we can't show any more information.
  end

  -- We need some validation js. A simplifying assumption is that we can only change settings or add on "oneshot" if we
  -- have completed all configs (well if the user has).
  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;

             var warning = document.getElementById("warning"+inputIdx);
             if (inputs[inputIdx].value == "")
             {
                 if (!warning)
                 {
                     warning = document.createElement("span");
                     warning.id = "warning"+inputIdx;
                     warning.innerHTML = " <img src='images/warning.png' alt='Cannot be blank' title='Cannot be blank'/>";
                     inputs[inputIdx].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>
  ]]

  content = content..[[
    <div class="formLayoutfull">
      <form action="platform_config.lua" method="post" onsubmit="return validateForm(this)">
        <h3>Communications forwarding</h3>
        <div>
          <label style="width: 150px; display: inline-block; text-align: right;">Address:</label>
          <input type="text" name="bibun_host_input" value="]]..bibun_host..[["]]..inputControl..[[/>
        </div>
        <div>
          <label style="width: 150px; display: inline-block; text-align: right;">Port:</label>
          <input type="text" name="bibun_port_input" value="]]..bibun_port..[["]]..inputControl..[[/>
        </div>
        <div>
          <label style="width: 150px; display: inline-block; text-align: right;">Inbox interval (seconds):</label>
          <input type="text" name="bibun_inbox_interval_input" value="]]..bibun_inbox_interval..[["]]..inputControl..[[/>
        </div>
        <br><hr>
        <input type="submit" name="submitPlatformButton" value="Save and Update"]]..buttonControl..[[/ onclick="doValidate = 1;">
  ]]

  if properties.hasChanged then
    content = content..[[
        <b><img src="images/ok.png"/> Changes saved.</b><br><br>
    ]]
  end

  content = content..[[
      </form>
      <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('bibunConfig'));">View ]]..remote_access_conf.bibunconfig_path..[[</a></a><br>
      <div id="bibunConfig" style="display: none;">
        <pre class="formLayoutfull">]]..properties.configText..[[
        </pre>
      </div>
    </div>
  ]]

  return content
end -- generateServerConfigContent

--
-- Generate the final webpage and send it along.
--
header = layout.getHeader()
content = generateServerConfigContent()
footer = layout.getFooter()
print(header..content..footer)
