/**
 * @module tgam-modal-methods
 */

/**
 * @method focusOnElement
 * @description if element exists and is visible, it will become focused
 * @param {string} element
 * @return {boolean}
 */
export function focusOnElement(element) {
  return element && element.offsetHeight !== 0 && element.focus();
}

/**
 * @method toArray
 * @description converts and array like (nodelist) to an array
 * @param val {Array|NodeList}
 * @return {Array}
 */
export function toArray(val) {
  if (typeof val === "undefined") {
    return null;
  } else if (typeof Array.from !== "undefined") {
    return Array.from(val);
  } else {
    return [].slice.call(val);
  }
}

/**
 * @method ariaToggle
 * @description will toggle aria expanded attribute on all matching elements
 * @param {string} selector
 * @param {string} ariaLabel
 * @param {boolean} value
 * @return {undefined}
 */
export function ariaToggle(selector, ariaLabel, value) {
  const targetButtons = toArray(document.querySelectorAll(selector));

  targetButtons.forEach((m) => {
    const ariaExpandedValue = typeof value !== "undefined" ? value : false;
    m.setAttribute("aria-expanded", ariaExpandedValue);

    if (ariaLabel) {
      const buttonText = m.querySelector(".c-control__button-text");
      buttonText.innerText = ariaLabel;
    }
  });
}

/**
 * @method getScrollbarWidth
 * @description gets the scrollbar width
 * @return {number}
 */
export function getScrollbarWidth() {
  var scrollDiv = document.createElement("div");
  scrollDiv.className = "u-scrollbar-measure";
  document.body.appendChild(scrollDiv);

  const scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;

  document.body.removeChild(scrollDiv);

  return scrollbarWidth;
}
