/*!
 * Copyright (c) 2021 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>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import $ from 'jquery';
import 'jquery-match-height';
import getMembers from '../api/eclipsefdn.members';
import template from './templates/member.mustache';

const EclipseFdnMembersList = (async () => {
  let membersListArray = [];
  const divArray = document.querySelectorAll('.eclipsefdn-members-list');

  // Use for loop instead of array.forEach or $().each to make sure
  // the following fetch won't be executed before the current one is done
  // so that the filter logic can work properly
  for (let index = 0; index < divArray.length; index++) {
    const element = divArray[index];
    let url = 'https://api.eclipse.org/public/member?pagesize=100';

    const isRandom = element.getAttribute('data-ml-sort') === 'random';

    const level = element.getAttribute('data-ml-level');
    if (level) {
      level.split(',').forEach((element) => {
        url += '&level[]=' + element.trim();
      });
    }

    const wg = element.getAttribute('data-ml-wg');
    if (wg) {
      url += '&working_group=' + wg;
    }

    let members = await getMembers(url);

    // Filter out the duplicated ones
    members = members.filter((member) => !membersListArray.find((item) => item.id === member.id));

    if (isRandom) {
      let tempArray = members.map((item) => item);
      const randomItems = [];
      members.forEach(() => {
        const randomIndex = Math.floor(Math.random() * tempArray.length);
        randomItems.push(tempArray[randomIndex]);
        tempArray.splice(randomIndex, 1);
      });
      members = randomItems;
    }

    membersListArray = [...membersListArray, ...members];

    element.innerHTML = template({
      items: members,
    });
    $.fn.matchHeight._applyDataApi();
  }
})();
export default EclipseFdnMembersList;
