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

import { getOrganizationById } from '../api/eclipsefdn.membership';
import renderTemplate from './templates/render-template';
import defaultTemplate from './templates/member-logo/default.mustache';
import loadingTemplate from './templates/loading-icon.mustache';

const templates = {
  default: defaultTemplate,
}

interface MemberLogoOptions {
  id?: string;
  templateId?: string;
}

const defaultOptions: MemberLogoOptions = {
  templateId: 'default',
};

const renderAll = async () => {
  const elements: HTMLElement[] = Array.from(document.querySelectorAll('.eclipsefdn-member-logo'));
  return Promise.allSettled(elements.map((element) => render(element)));
}

const render = async (element?: HTMLElement) => {
  element = element ?? document.querySelector('.eclipsefdn-member-logo');
  if (!element) return;

  const options: MemberLogoOptions = { ...defaultOptions, ...element.dataset };

  // Validate whether organization id was given.
  if (!options.id) {
    console.error('No organization id provided to eclipsefdn-member-logo');
    return;
  };
  
  // Validate and convert organization id into a number.
  let organizationId: number;
  try {
    organizationId = parseInt(options.id);
  } catch {
    console.error('Invalid organization id provided to eclipsefdn-member-logo');
    return;
  }
  
  // Set the loading template.
  element.innerHTML = loadingTemplate({ inline: true });
  
  // Retrieve the organization and handle possible error.
  const [organization, error] = await getOrganizationById(organizationId); 
  if (error) {
    console.error('An error occurred when retrieving organization id', error);
    // Clear the contents.
    element.innerHTML = '';
    return;
  }
  
  const data = {
    logo: organization.logos.web,
    name: organization.name,
  };

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

export default { render, renderAll };
