// This assumes docker_consumer.js is imported

/**
 * Sets up the form submission listener which sends a message via WebSocket when the form is submitted.
 * @param {WebSocket} ws - WebSocket connection to send submitted messages to
 * @param {function(): boolean} getDockerReady - Function to check if Docker is ready (deny submission otherwise)
 */
function setupFormListener(ws, getDockerReady) {
  const formElement = document.getElementById("login-form");
  formElement.addEventListener("submit", (e) => {
    // Prevent normal form submission
    e.preventDefault();

    const formElement = e.target;
    const errorsDivElement = formElement.querySelector("#login-form-errors");

    // Handle submission attempt before the container is ready
    if (!getDockerReady()) {
      errorsDivElement.style.display = "block"; // make errors div visible
      errorsDivElement.innerHTML = '<ul clas="m-0"><li>Docker connection is not ready.</li></ul>';
      return;
    }
    errorsDivElement.style.display = "none"; // make errors div invisible

    // Send the message to the server
    const email = formElement.email.value;
    const password = formElement.password.value;
    ws.send(JSON.stringify({ type: "login-data", email: email, password: password }));
  });
}

/**
 * Callback function to handle non-status messages relayed from `setupWebSocket` function.
 * @param {WebSocket} ws - WebSocket connection used for sending responses if needed.
 * @param {WebSocketMessage} msgData - Data received from WebSocket, triggering this callback function
 */
function messageCallback(ws, msgData) {
  const resultElement = document.getElementById("docker-ws-results");

  // Reset the result element with the new data
  // This introduces a 200ms delay, during which the data is cleared.
  // This is done to make it obvious that the content is being updated.
  const reset = (data) => {
    resultElement.innerHTML = "";
    setTimeout(() => {
      resultElement.innerHTML = data;
    }, 200);
  };

  switch (msgData.type) {
    case "login.exec_error":
      reset(
        '<div data-toggle="tooltip" style="cursor: pointer;" title="This is not an error in the DEMO portal, it is an intentional error that occured within this scenario. Don\'t actually report it anywhere."><span style="color: red;"><p><i class="fa-solid fa-exclamation-circle"></i> ' +
        msgData.message +
        "</p></span><p>Command: </p><code>" +
        msgData.command +
        '</code></p><p>Captured output:</p><pre style="background-color: #f8f9fa; border: 1px solid #ccc; padding: 10px; overflow: auto;">' +
        msgData.output +
        "</pre></div>",
      );
      break;
    case "login.error":
      reset(
        '<span style="color: red;"><p><i class="fa-solid fa-exclamation-circle"></i> ' +
        msgData.message +
        '</p></span><p>Captured output:</p><pre style="background-color: #f8f9fa; border: 1px solid #ccc; padding: 10px; overflow: auto;">' +
        msgData.output +
        "</pre>",
      );
      break;
    case "login.invalid_credentials":
      reset('<span style="color: red;"><p>' + msgData.message + "</p></span>");
      break;
    case "login.success":
      reset("");
      //reset('<span style="color: green;"><p>' + msgData.message + "</p></span>");

      // Submit the hidden submission form, which will make the browser
      // send a POST request to the server and show the user the returned page.
      //
      // This form will contain a token that was received from the server
      // as a part of this message.
      const form = document.getElementById("submission-form");
      const tokenInput = document.getElementById("submission-token");
      tokenInput.value = msgData.token;
      form.submit();
      break;
    default:
      console.warn("Got unknown message type: " + msgData.type + " message: " + msgData.message);
  }
}

const { ws, getDockerReady } = setupWebSocket(messageCallback, 8);
setupFormListener(ws, getDockerReady);
