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

import jQuery from 'jquery';
import templateLoading from './templates/loading-icon.mustache';
import getParticipatingOrganizations from '../api/eclipsefdn.participating-organizations';
import template from "./templates/participating-organizations.mustache";

const alphabeticalComparator = (a, b) => a.name.toUpperCase() > b.name.toUpperCase() ? 1 : -1;

const EclipseFdnParticipatingOrganizations = (async function ($, document) {
    const element = document.querySelector('.eclipsefdn-participating-organizations');
    if (!element) return;

    element.innerHTML = templateLoading();

    const baseUrl = 'https://membership.eclipse.org/api/projects';

    const projectShortId = element.getAttribute('data-project-short-id');

    if (!projectShortId) return;

    const url = `${baseUrl}/${projectShortId}/organizations`;

    let participatingOrganizations = await getParticipatingOrganizations(url);

    if (!participatingOrganizations) return;

    participatingOrganizations = participatingOrganizations.sort(alphabeticalComparator);

    const data = {
        items: participatingOrganizations
    };

    element.innerHTML = template(data);
})(jQuery, document);

export default EclipseFdnParticipatingOrganizations;
