/*
 * Remove active class on both elements: link and content
 */
let resetActive = function (links, contents) {
  for (items of [links, contents]) {
    items.forEach(function (item) {
      if (item.classList.contains("active")) {
        item.classList.remove("active");
      }
    });
  }
};

/*
 * Count links array and return rank of given link
 */
let countNewActive = function (links, link) {
  let rank = 0;
  for (let i = 0; i < links.length; ++i) {
    rank++;
    if (links[i] == link) {
      return rank;
    }
  }
};

/*
 * Set class active on both new elements: link and content
 */
let setNewActive = function (links, contents, rank) {
  if (!links[rank - 1]) {
    rank = 1;
  }
  link = links[rank - 1];

  link.classList.add("active");

  count = 0;
  contents.forEach(function (pane) {
    count++;
    if (rank == count) {
      pane.classList.add("active");
    }
  });
};

/*
 * Set height of content pane
 */
let setPaneHeight = function (contents) {
  contents.forEach(function (pane) {
    // let computedStyle = getComputedStyle(pane);
    // console.log(computedStyle.height);
    // comment prendre la hauteur d'une div masquée avec display:none
  });
};

/*
 * Check if links are defined in controller
 * If true, disable javascript listener
 */
let isLinkRef = function (link) {
  if (link.getAttribute("href") == "#") {
    return false;
  }
  return true;
};

/*
 * Main function
 */
window.addEventListener("load", function () {
  tabParams.forEach(function (unit) {
    let tabPanel = document.querySelector("#" + unit.id);
    if (tabPanel) {
      let nav = tabPanel.querySelector("nav"),
        tabs = nav.querySelectorAll("ul.nav-tabs li.nav-item"),
        links = nav.querySelectorAll("ul.nav-tabs li.nav-item a.nav-link"),
        contents = tabPanel.querySelectorAll("div.tab-content div.tab-pane");
      if (unit.type == "pill") {
        tabPanel.classList.add("pills");
      }

      if (!unit.initPane) {
        unit.initPane = 1;
      }

      setPaneHeight(contents);

      // initial position
      setNewActive(links, contents, unit.initPane);

      // listen
      links.forEach(function (link) {
        if (isLinkRef(link) == false) {
          link.addEventListener("click", function () {
            resetActive(links, contents);
            setNewActive(links, contents, countNewActive(links, link));
          });
        }
      });
    }
  });
});
