/*!
 * Copyright (c) 2021, 2022 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:
 *   Christopher Guindon <chris.guindon@eclipse-foundation.org>
 *   Eric Poirier <eric.poirier@eclipse-foundation.org>
 *   Zhou Fang <zhou.fang@eclipse-foundation.org>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import { displayErrMsg } from './utils';
import template from './templates/explore-working-groups/working-group-list.mustache';
import templateLoading from './templates/loading-icon.mustache';

const render = async () => {
  const element = document.querySelector('.eclipsefdn-wgs-list');
  if (!element) {
    return;
  }
  element.innerHTML = templateLoading();

  let url = 'https://api.eclipse.org/working-groups';
  let wgsData;
  try {
    wgsData = await (await fetch(url)).json();

    // Filter out working groups which have OpenHW as parent organization. e.g.
    // OpenHW Group, OpenHW Group Europe and OpenHW Group Asia
    wgsData = wgsData.filter((workingGroup) => workingGroup?.parent_organization !== 'ohwg');

    // Remove any non-word characters from title while sorting
    const removeNonWordChars = wgTitle => wgTitle.replaceAll(/\W/gi, '');
    wgsData = wgsData.sort((a, b) => removeNonWordChars(a.title).localeCompare(removeNonWordChars(b.title)));

  } catch (error) {
    displayErrMsg(element, error);
    return;
  }

  /** 
    * Strips the "Working Group" substring from the title.
    * 
    * @returns {string} - The title without the "Working Group" substring.
    */
  const populateWGNames = function () {
    return this.title.replace(' Working Group', '');
  };

  const populateIds = function () {
    // Need to keep using those ids as they are used/referred on some other places
    const oldWGIds = {
      aice: 'aice-working-group',
      gemoc: 'gemoc-rc',
      'internet-things-iot': 'internet-of-things',
      sdv: 'software-defined-vehicle',
    };
    const oldId = oldWGIds[this.alias];
    return oldId ? oldId : this.alias;
  };

  const checkStatus = function () {
    switch (this.status) {
      case 'active':
        return 'Active';
      case 'proposed':
        return 'Proposed';
      case 'incubating':
        return 'Incubating';
      default:
        // Won't show wg that is inactive or in any invalid status
        return false;
    }
  };

  let filterOptionsArray = ['active', 'proposed', 'incubating'];
  // Keep those that exist in response data
  filterOptionsArray = filterOptionsArray.filter((option) => wgsData.find((wg) => wg.status.toLowerCase() === option));
  const filterOptions = {
    // Only show filter when there are 2 or more status in response data
    all: filterOptionsArray.length > 1,
    active: filterOptionsArray.includes('active'),
    proposed: filterOptionsArray.includes('proposed'),
    incubating: filterOptionsArray.includes('incubating'),
  };

  element.innerHTML = template({
    sections: wgsData,
    populateWGNames,
    populateIds,
    checkStatus,
    shouldShowFilterOptions: filterOptions,
  });

  const anchoredWG = window.location.hash.replace('#', '');
  anchoredWG && document.getElementById(anchoredWG).scrollIntoView({ behavior: 'smooth' });

  // Filter logic
  let currentSelectedStatus = 'wg-item';
  const allFilterBtns = document.querySelectorAll('.wg-btn');
  allFilterBtns[0]?.classList.add('active');

  const fadeOutAndIn = ({ target }) => {
    const newSelectedStatus = target.getAttribute('data-wg');
    if (newSelectedStatus === currentSelectedStatus) {
      // No need to do filtering if the status doesn't change
      return;
    }

    // Fade out current wg items
    document.querySelectorAll(`.${currentSelectedStatus}`).forEach((item) => {
      item.classList.add('fade');
      setTimeout(() => {
        item.classList.add('hide');

        // Fade in selected wg items
        document.querySelectorAll(`.${newSelectedStatus}`).forEach((item) => {
          item.classList.remove('hide');
          item.classList.remove('fade');
        });
      }, 150);
    });

    allFilterBtns.forEach((btn) => {
      if (btn.getAttribute('data-wg') === currentSelectedStatus) {
        btn.classList.remove('active');
      }
    });
    target.classList.add('active');
    currentSelectedStatus = newSelectedStatus;
  };

  allFilterBtns.forEach((wgBtn) => {
    wgBtn.addEventListener('click', fadeOutAndIn);
  });
};

export default { render };
