/*!
 * 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 $, { type } from 'jquery';
import Mustache from 'mustache';
import 'jquery-match-height';
import template from './templates/tpl-projects-item.mustache';
import "numeral";
import List from 'list.js';
import getProjectsData from "../api/eclipsefdn.projects"

const EclipseFdnProjects = (async () => {

    const element = document.querySelector('.featured-projects');
    if (!element) {
        return;
    }

    const options = {
        id: '',
        templateId: '',
        projectIds: '',
        url: '',
        isStaticSource: false,
        ...$(element).data(),
    };

    function fetchCategories() {
        let elem = document.getElementById('projects-categories');
        if (elem !== null) {
            let categoriesUrl = elem.getAttribute('data-categories');
            return fetch(categoriesUrl).then(response => response.json());
        }

        // returning an empty promise if categories were not passed.
        return async () => { };
    }

    let projectsData = await getProjectsData(options.url, options.isStaticSource);
    let resultsProjects = [];
    let resultsCategories = [];
    Promise.allSettled([projectsData, fetchCategories()])
        .then(function (responses) {
            if (responses[0].status === 'fulfilled') {
                const projects = responses[0].value;
                if (projects.length > 0) {
                    resultsProjects = projects;
                }
            }

            if (responses[1].status === 'fulfilled') {
                resultsCategories = responses[1].value;
            }

            $(resultsProjects).each(function (key, project) {

                // Populate the Tags array
                if (resultsCategories.length <= 0 && typeof resultsProjects[key].tags !== "undefined") {
                    const project_tags = resultsProjects[key].tags;
                    if (project_tags.length !== 0) {
                        tags[resultsProjects[key].project_id] = project_tags;
                    }
                }

                const category = getCategory(resultsCategories, resultsProjects[key].project_id);
                resultsProjects[key].category = category.toString();
            });

            const data = {
                items: resultsProjects,
            };

            // Render component
            let html = '';
            if (options.templateId !== '' && document.getElementById(options.templateId)) {
                const theme = document.getElementById(options.templateId).innerHTML;
                html = Mustache.render(theme, data);
            } else {
                html = template(data);
            }
            element.innerHTML += html;

            if (resultsCategories.length <= 0) {
                resultsCategories = tags;
            }

            $.each(resultsCategories, function (key, projects) {
                $.each(projects, function (key, value) {
                    let duplicate = $('.eclipsefdn-project-list-filters').find("button:contains('" + value + "')");
                    if (duplicate.length > 0) {
                        return;
                    }
                    let button = document.createElement('button');
                    button.innerHTML = value;
                    button.className = 'btn btn-filter-project';
                    button.setAttribute('data-toggle', 'button');
                    $('.eclipsefdn-project-list-filters').append(button);
                });
            });

            const values = {
                valueNames: [
                    'name',
                    'category'
                ],
            };

            let list = new List('projects-list', values);

            $('.btn-filter-project').on('click', function (elem) {
                $('.btn-filter-project').not(this).each(function () {
                    $(this).removeClass('active');
                });
                setTimeout(function () {
                    list.filter(computeFilterFunction);
                }, 10);
            });

            $.fn.matchHeight._applyDataApi();
        })
        .catch(err => console.log(err));


    let tags = {};

    let getCategory = function (categories, project_id) {
        let category = "Other Tools";
        if (typeof categories[project_id] !== "undefined") {
            category = categories[project_id];
        }
        if (categories.length <= 0 && typeof tags[project_id] !== "undefined") {
            category = tags[project_id].toString().split(',').join(', ');
        }
        return category;
    }

    let computeFilterFunction = function (item) {
        let filter = [];
        $('.btn-filter-project').each(function (index, elem) {
            if ($(elem).hasClass('active')) {
                filter.push($(elem).text());
            }
        });
        if (filter.length == 0) {
            return true;
        }
        let found = false;
        for (let i = 0; i < filter.length; i++) {
            const element = filter[i];
            if (typeof item.values().category !== "undefined" && item.values().category.indexOf(element) !== -1) {
                found = true;
                continue;
            }
            found = false;
            break;
        }
        return found;
    };
})();

export default EclipseFdnProjects;
