/*!
 * Copyright (c) 2021, 2022, 2023, 2024 Eclipse Foundation, Inc.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * Contributors:
 *   Zhou Fang <zhou.fang@eclipse-foundation.org>
 *   Eric Poirier <eric.poirier@eclipse-foundation.org>
 *   Olivier Goulet <olivier.goulet@eclipse-foundation.org>
 * 
 * SPDX-License-Identifier: EPL-2.0
 */

/**
  * Display all elements.
  *
  * @param elements - An array of HTML elements to display.
  */
export const showAll = (elements: HTMLElement[]): void => {
  elements.forEach((element) => element.classList.remove('hidden'));
}

/**
  * Removes the active class to all elements.
  *
  * @param elements - An array of HTML elements to remove the active classes
  * from.
  */
export const deactivateAll = (elements: HTMLElement[]): void => {
  elements.forEach((element) => element.classList.remove('active'));
}

/**
  * Toggles the visibility of an element.
  *
  * @param condition - If true, the element will display. If false, the element
  * will be hidden. If no condition is given, the element will simply toggle.
  */
export const toggleVisibility = (element: HTMLElement, condition?: boolean): void => {
  if (condition === true) {
    element.classList.remove('hidden');
  } else if (condition === false) {
    element.classList.add('hidden');
  } else {
    element.classList.toggle('hidden');
  }
}

export const displayErrMsg = (element: HTMLElement, err = '', errText = 'Sorry, something went wrong, please try again later.') =>
  (element.innerHTML = `<div class="alert alert-danger" role="alert"><p><strong>Error ${err}</strong></p> <p>${errText}</p></div>`);

export const scrollToAnchor = () => {
  const elementId = location.hash.replace('#', '');
  const element = document.getElementById(elementId);

  if (!element) return;

  element.scrollIntoView();
}

/** Resolves when the given element has finished rendering its children.
  * @param element
  */
export const waitForRender = (element: HTMLElement | Node): Promise<void> => {
  return new Promise(resolve => {
    // If the element already has children nodes, it's already rendered
    if (element.childNodes?.length > 0) {
      resolve();
      return;
    }
    
    // Otherwise, wait for the element to have children
    const observer = new MutationObserver((mutationList, observer) => {
      for (const mutation of mutationList) {
        if (mutation.type === 'childList') {
          observer.disconnect();
          resolve();
        }
      }
    });

    observer.observe(element, { childList: true });
  });
};

