<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Main page</title>
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link rel="stylesheet" href="/css/styles.css" />
  </head>
  <body>
    <main>
      <p class="loadingText">Loading...</p>
      <section class="announcementsHolder">
        <label
          >Search here:
          <input
            list="searchResults"
            name="search"
            id="search"
            autocomplete="off"
        /></label>
        <div id="searchResults"></div>

        <hr />
        <button onclick="javascript:location = `/createAnnouncement`">
          Create announcement
        </button>
      </section>
    </main>
  </body>
  <script>
    const debounce = (func, timeout = 300) => {
      let timer;
      return (...args) => {
        clearTimeout(timer);
        timer = setTimeout(() => {
          func.apply(this, args);
        }, timeout);
      };
    };

    const performSearch = async () => {
      const searchResultsHolder = document.getElementById("searchResults");
      searchResultsHolder.innerHTML = "";

      let text = document.getElementById("search").value.trim();
      if (text.length == 0) return;

      const data = await (
        await fetch("/api/search", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ text }),
        })
      ).json();

      if (data.ok) {
        if (data.result.length === 0) {
          searchResultsHolder.innerHTML = "<b>No results!</b>";
        } else {
          searchResultsHolder.innerHTML = data.result
            .map((e) => `<a href="/${e._id}">${e.title}</a>`)
            .join("<br>");
        }
      } else {
        alert(data.error);
      }

      console.log(data);
    };

    const load = async () => {
      const loadingText = document.querySelector(".loadingText");
      const announcementsHolder = document.querySelector(
        ".announcementsHolder"
      );

      loadingText.hidden = false;
      announcementsHolder.hidden = true;

      try {
        const data = await (await fetch("/api/announcements")).json();
        for (const ancmt of data.announcements) {
          const el = document.createElement("div");

          const title = document.createElement("a");
          title.innerHTML = `<b>${ancmt.title}</b>`;
          title.href = `/${ancmt._id}`;

          el.appendChild(title);
          announcementsHolder.appendChild(el);
        }
      } catch (e) {
        alert(e);
      }

      loadingText.hidden = true;
      announcementsHolder.hidden = false;

      document.getElementById("search").addEventListener(
        "change",
        debounce(() => performSearch())
      );
    };

    document.addEventListener("DOMContentLoaded", load);
  </script>
</html>
