/*!
 * Copyright (c) 2021, 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 templateLoading from './templates/loading-icon.mustache';
import defaultTemplate from "./templates/logo-list.mustache";
import { getProjectParticipatingOrganizations } from '../api/eclipsefdn.membership';
import renderTemplate from './templates/render-template';

const defaultOptions = {
    templateId: 'default',
    projectShortId: undefined
};

const templates = {
    default: defaultTemplate
};

const render = async () => {
    const element = document.querySelector('.eclipsefdn-participating-organizations');
    if (!element) return;

    element.innerHTML = templateLoading();

    const options = { ...defaultOptions, ...element.dataset };
    if (!options.projectShortId) return;

    let [participatingOrganizations] = await getProjectParticipatingOrganizations(options.projectShortId);
    if (!participatingOrganizations) return;

    const data = {
        items: participatingOrganizations.map(organization => ({
            id: organization.organizationId,
            name: organization.name,
            logo: organization.logos.web
        }))
    };

    await renderTemplate({
      element, 
      templates, 
      templateId: options.templateId, 
      data
    });
};

const eclipsefdnParticipatingOrganizations = {
    render
};

export default eclipsefdnParticipatingOrganizations;
