import * as Users from "/components/users/users.js";
import * as Management from "/components/management/management.js";
import * as Votes from "/components/vote/vote-page.js";
import * as Visualization from "/components/visualization/visualization-page.js";
import * as Login from "/components/login/login.js";
import * as Navbar from "/components/navbar/navbar.js";
import * as Helper from "/components/help/help.js";
import { AnimateCSS } from "/services/common/common.js";

const mountPoint = document.getElementById("main");
const spinner = document.getElementById("spinner");

document.addEventListener("DOMContentLoaded", function () {
  Navbar.mount("navbar");
  window.addEventListener("hashchange", navigate);
  navigate();
});

async function navigate() {
  window.clearInterval(window.intervalRefreshResults);
  switch (location.hash) {
    case "#votes":
      load(mountPoint, async function () {
        await Votes.mount("main");
      });
      break;
    case "#visualization":
      load(mountPoint, async function () {
        await Visualization.mount("main");
      });
      break;
    case "#users":
      load(mountPoint, async function () {
        await Users.mount("main");
      });
      break;
    case "#management":
      load(mountPoint, async function () {
        await Management.mount("main");
      });
      break;
    case "#login":
      load(mountPoint, async function () {
        await Login.mount("main");
      });
      break;
    case "#help":
      load(mountPoint, async function () {
        await Helper.mount("main");
      });
      break;
    default:
      location.hash = "#visualization";
      break;
  }
}

async function load(element, domAlteration) {
  AnimateCSS(element, "fadeOut", async function () {
    element.classList.add("is-hidden");
    spinner.classList.remove("is-hidden");
    AnimateCSS(spinner, "fadeIn");
    if (typeof domAlteration === "function") {
      await domAlteration();
      AnimateCSS(spinner, "fadeOut", function () {
        spinner.classList.add("is-hidden");
      });
      element.classList.remove("is-hidden");
      AnimateCSS(element, "fadeIn");
    }
  });
}