// 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("tz-convert-form");
  formElement.addEventListener("submit", (e) => {
    // Prevent normal form submission
    e.preventDefault();

    const formElement = e.target;
    const errorsDivElement = formElement.querySelector("#tz-convert-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 timezone = formElement.timezone.value;
    const time = formElement.time.value;
    ws.send(JSON.stringify({ type: "tz-convert", timezone: timezone, time: time }));
  });
}

/**
 * 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("tz-convert-result");

  switch (msgData.type) {
    case "tz-convert.pending_exec":
      resultElement.innerHTML = '<div><i class="fa-solid fa-spinner fa-spin"></i> Waiting for server...</div>';
      break;
    case "tz-convert.exec_result":
      resultElement.innerHTML = '<div><pre><i class="fa-regular fa-clock"></i> ' + msgData.message + "</pre></div>";
      break;
    case "tz-convert.exec_error":
      resultElement.innerHTML =
        '<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>Captured output:</p><pre style="background-color: #f8f9fa; border: 1px solid #ccc; padding: 10px; overflow: auto;">' +
        msgData.output +
        "</pre></div>";
      break;
    default:
      console.warn("Got unknown message type: " + data.type + " message: " + msgData.message);
  }
}

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