/*!
 * 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:
 *   Eric Poirier <eric.poirier@eclipse-foundation.org>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import Mustache from 'mustache';
import templateLoading from './templates/loading-icon.mustache';
import 'jquery-match-height';
import template from './templates/tpl-news-tag-item.mustache';
import "numeral";
import getNewsData from "../api/eclipsefdn.news"

const EclipseFdnNewsTags = (async () => {

    const element = document.querySelector('.news-tags-sidebar');
    if (!element) {
        return;
    }

    element.innerHTML = templateLoading();

    const options = {
      ...element.dataset,
    };

    let newsData = await getNewsData(options.url, []);

    let tagTitles = [];
    let dataTags = [];

    Promise.allSettled([newsData])
    .then(function (responses) {
        if (responses[0].status === 'fulfilled') {
          const news = responses[0].value;
          if (news.length > 0) {

            // Go through each news items
            news.forEach((newsItem) => {
              tagTitles = tagTitles.concat(newsItem.tags);
            });

            // Counting each tags
            let counts = {};
            for (const title of tagTitles) {
              counts[title] = counts[title] ? counts[title] + 1 : 1;
            }

            // Build dataTags array for mustache
            let uniqueTags = [...new Set(tagTitles)];
            uniqueTags.forEach((tag) => {
              let array = {};
              array.title = tag;
              array.count = counts[tag];

              const urlSegments = window.location.href.split( '?' );
              const currentPath = urlSegments[0].replace(/\/+$/, '');
              array.url = currentPath + '?news_tags=' + tag;
              dataTags = dataTags.concat(array);
            });
          }
        }

        const data = {
          items: dataTags,
        };

        // Render component
        element.innerHTML = template(data);
    })
    .catch(err => console.log(err));

})();

export default EclipseFdnNewsTags;
