/*!
 * Copyright (c) 2022 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>
 *
 * 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 parse from 'parse-link-header';
import { displayErrMsg } from '../utils/utils';

const eclipseFdnResources = async () => {
  const resourcesElements = document.querySelectorAll('.newsroom-resources');
  if (!resourcesElements || resourcesElements.length === 0) {
    return;
  }

  const resLink = function (linkType, item) {
    if (linkType === 'direct') {
      return item.direct_link
        ? ({ link: item.direct_link || '', icon: 'pdf', type: 'PDF' })
        : ({ link: item.landing_link || '', icon: 'text', type: 'HTML' });
    }
    return item.landing_link
      ? ({ link: item.landing_link || '', icon: 'text', type: 'HTML' })
      : ({ link: item.direct_link || '', icon: 'pdf', type: 'PDF' });
  };

  resourcesElements.forEach(async (resourcesElement) => {
    let hasError = false;
    const titles = resourcesElement.getAttribute('data-res-title')?.replaceAll(', ', ',')?.split(',');
    const resourceTypes = resourcesElement.getAttribute('data-res-type')?.replaceAll(', ', ',')?.split(','); 
    const viewMoreLinks = resourcesElement.getAttribute('data-res-view-more')?.replaceAll(', ', ',')?.split(',');
    let resourcesData = [];
    resourceTypes.forEach((resourceType, index) => {
      let title;
      if (titles) title = titles[index];

      resourcesData.push({
        title,
        resourceType,
        viewMoreLink: viewMoreLinks?.[index],
        data: [],
        isFetching: true,
      });
    });

    const formatDate = function () {
      let theDate = new Date(this.date).toDateString();
      theDate = theDate.slice(0, 3) + ',' + theDate.slice(3);
      return theDate;
    };

    const displayDataOnPage = (data) => {
      switch (resourcesElement.getAttribute('data-res-template')) {
        case 'list':
          resourcesElement.innerHTML = templateResourceList({
            items: data,
            resLink: function () {
              return resLink(resourcesElement.getAttribute('data-res-link'), this);
            },
          });
          break;
        case 'image':
          const skipItems = resourcesElement.getAttribute('data-res-skip');
          if (skipItems) {
            data.forEach((item) => item.data.splice(0, skipItems));
          }
          resourcesElement.innerHTML = templateResourceImage({
            items: data,
            resClass: resourcesElement.getAttribute('data-res-class'),
            resLink: function () {
              return resLink(resourcesElement.getAttribute('data-res-link'), this);
            },
          });
          break;
        case 'image-with-title':
          resourcesElement.innerHTML = templateResourceImageWithTitle({
            items: data,
            resClass: resourcesElement.getAttribute('data-res-class'),
            resLink: function () {
              return resLink(resourcesElement.getAttribute('data-res-link'), this);
            },
            formatDate,
          });
          break;
        default:
          break;
      }
    };

    const fetchWithPagination = async (resource, index) => {
      let data = [];
      const pagesizeAttribute = resourcesElement.getAttribute('data-res-limit');
      const pagesize = pagesizeAttribute || 100;
      let url = `https://newsroom.eclipse.org/api/resources?pagesize=${pagesize}&parameters[publish_to]=${resourcesElement.getAttribute(
        'data-res-wg'
      )}&parameters[resource_type][]=${resource.resourceType}&page=1`;
      const getData = async () => {
        try {
          let response = await fetch(url);
          if (response.ok) {
            let newData = await response.json();
            data = [...data, ...newData.resources];
            const links = parse(response.headers.get('link'));
            if (links?.next?.url && !pagesizeAttribute) {
              url = links.next.url;
              await getData();
            }
            return;
          }
          hasError = true;
          displayErrMsg(resourcesElement, response.status);
        } catch (error) {
          console.log(error);
          hasError = true;
          displayErrMsg(resourcesElement, error);
        }
      };

      await getData();

      if (hasError) {
        return;
      }
      resourcesData[index] = { ...resourcesData[index], isFetching: false, data };
    };

    resourcesElement.innerHTML = templateResourceList({
      items: resourcesData,
    });

    await Promise.all(resourcesData.map((item, index) => fetchWithPagination(item, index)));

    if (hasError) {
      return;
    }
    displayDataOnPage(resourcesData);
  });
};

document.addEventListener('DOMContentLoaded', eclipseFdnResources);

export default eclipseFdnResources;
