/*!
 * Copyright (c) 2022, 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:
 *   Zhou Fang <zhou.fang@eclipse-foundation.org>
 *   Olivier Goulet <olivier.goulet@eclipse-foundation.org>   
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import templateResourceList from './templates/newsroom-resources/resources-list.mustache';
import templateResourceImage from './templates/newsroom-resources/resources-image.mustache';
import templateResourceImageWithTitle from './templates/newsroom-resources/resources-image-with-title.mustache';
import templateResourceCover from './templates/newsroom-resources/resources-cover.mustache';
import { getNewsroomResources } from '../api/eclipsefdn.newsroom';
import renderTemplate from './templates/render-template';

const templates = {
  list: templateResourceList,
  image: templateResourceImage,
  'image-with-title': templateResourceImageWithTitle,
  cover: templateResourceCover,
}

// Converts a string date to a more readable format.
const formatDate = (dateStr) => {
  let date = new Date(dateStr).toDateString();
  date = date.slice(0, 3) + ',' + date.slice(3);

  return date;
};

// Get the link and icon for the resource item.
const linkReducer = (linkType, newsroomResource) => {
  switch (linkType) {
    case 'direct':
      return newsroomResource.directLink
        ? ({ link: newsroomResource.directLink || '', icon: 'pdf', type: 'PDF' })
        : ({ link: newsroomResource.landingLink || '', icon: 'text', type: 'HTML' });
    default:
      return newsroomResource.landingLink
        ? ({ link: newsroomResource.landingLink || '', icon: 'text', type: 'HTML' })
        : ({ link: newsroomResource.directLink || '', icon: 'pdf', type: 'PDF' });
  }
}

const render = async () => {
  const resourcesElements = Array.from(document.querySelectorAll('.newsroom-resources'));
  if (resourcesElements.length === 0) return;

  await Promise.all(resourcesElements.map(async resourcesElement => {
    const pageSizeDataAttribute = resourcesElement.dataset.pageSize || resourcesElement.dataset.resLimit;

    const options = { 
      resourceTypes: resourcesElement.dataset.resType
        ?.replaceAll(', ', ',')
        .split(','),
      publishTo: resourcesElement.dataset.resWg
        ?.replaceAll(', ', ',')
        .split(','),
      viewMoreLinks: resourcesElement.dataset.resViewMore
        ?.replaceAll(', ', ',')
        .split(','),
      titles: resourcesElement.dataset.resTitle
        ?.replaceAll(', ', ',')
        .split(','),
      linkType: resourcesElement.dataset.resLink,
      templateId: resourcesElement.dataset.resTemplate,
      pageSize: pageSizeDataAttribute ? parseInt(pageSizeDataAttribute) : null,
      skip: resourcesElement.dataset.resSkip ? parseInt(resourcesElement.dataset.resSkip) : 0,
    };
 
    // If the template displays types as separate sections, we would need to alter the way we fetch data.
    const hasSections = options.templateId === 'list';
    
    let newsroomResources;
    let newsroomResourcesGroupedBySection = {};
    let error;

    if (hasSections) {
      const results = await Promise.all(options.resourceTypes.map(async resourceType => {
        let [newsroomResourcesOfSection] = await getNewsroomResources({
          resourceTypes: [resourceType],
          publishTo: options.publishTo,
          pageSize: options.pageSize && options.pageSize + options.skip,
        });

        return { resourceType, newsroomResources: newsroomResourcesOfSection };
      }));
      results.forEach(r => newsroomResourcesGroupedBySection[r.resourceType] = r.newsroomResources);
    } else {
      [newsroomResources, error] = await getNewsroomResources({
        resourceTypes: options.resourceTypes,
        publishTo: options.publishTo,
        pageSize: options.pageSize && options.pageSize + options.skip,
      });

      newsroomResources = newsroomResources.slice(options.skip);
    }


    let data;
    if (hasSections) {
      data = {
        items: options.resourceTypes.map((resourceType, i) => ({
          isFetching: false,
          title: options.titles[i],
          data: newsroomResourcesGroupedBySection[resourceType]
            .map(r => ({
              resClass: resourcesElement.getAttribute('data-res-class'),
              title: r.title,
              image: r.image,
              resLink: linkReducer(options.linkType, r),
            })),
        }))
      }
    } else {
      data = {
        items: {
          isFetching: false,
          title: options.titles[0],
          viewMoreLink: options.viewMoreLinks ? options.viewMoreLinks[0] : null,
          data: newsroomResources.map(r => ({
            resClass: resourcesElement.getAttribute('data-res-class'),
            title: r.title,
            image: r.image,
            date: formatDate(r.date),
            resLink: linkReducer(options.linkType, r),
          })),
        }
      }
    }

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

export default { render };
