/*!
 * Copyright (c) 2023 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:
 *   Olivier Goulet <olivier.goulet@eclipse-foundation.org>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import { getAds } from '../api/eclipsefdn.newsroom';
import defaultTemplate from './templates/promotion/default.mustache';
import renderTemplate from './templates/render-template';

const templates = {
  default: defaultTemplate
}

/**
  * This callback attempts to load ads in the mega menu if any are visible and
  * not already loaded.
  *
  * @type {MutationCallback}
  */
const attemptLoadingAds = (mutationList, observer) => {
  mutationList.forEach(async (mutation) => {
    const adElement = mutation.target.querySelector('.eclipsefdn-mega-menu-promo-content');
    if (!adElement) {
      return;
    };

    // If the ads have already been loaded, do nothing.
    if (adElement.classList.contains('loaded')) {
      return;
    }
    
    // If the mega menu is not hidden, attempt to load the ads.
    if (!mutation.target.classList.contains('hidden')) {
      adElement.classList.add('loaded');

      const [ads, error] = await getAds({
        formats: { ads_square: '1' },
        publishTo: 'eclipse_org_home',
      });
      
      // If there is an error, stop attempting to fetch ads. We do not want to
      // call the API over and over if the request is failing.
      if (error) {
        observer.disconnect();
        return;
      }
  
      // Render the ad in the mega menu.
      await renderTemplate(adElement, templates, 'default', ads[0]);
    }
  });
};

/**
  * The render function for the mega menu promo content widget.
  */
const render = () => {
  const observer = new MutationObserver(attemptLoadingAds);

  // Observe each mega menu submenu for changes to the class attribute.
  // We care about the `hidden` class. If it is not present, we want to try to
  // load ads if not already loaded.
  const subMenuElements = document.querySelectorAll('.eclipsefdn-mega-menu .mega-menu-submenu');
  subMenuElements.forEach(subMenuElement => observer.observe(subMenuElement, { 
    attributes: true, 
    attributeFilter: ['class'],
  }));
};

export default { render };
