/*
 * 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:
 *   Olivier Goulet <olivier.goulet@eclipse-foundation.org>
 *
 * SPDX-License-Identifier: EPL-2.0
 */

import defaultTemplate from './templates/video-list.mustache';
import loadingTemplate from './templates/loading-icon.mustache';
import renderTemplate from './templates/render-template';
import { youtube } from '../api/eclipsefdn.media-link';
import { renderVideos } from '../privacy/eclipsefdn.videos';

const defaultOptions = {
    templateId: 'default',
    channel: 'eclipsefdn',
    playlistIds: '',
    tags: [],
    descriptionMaxLength: 200
}

const templates = {
    default: defaultTemplate
}

const render = async () => {
    const element = document.querySelector('.eclipsefdn-video-list');
    if (!element) return;

    element.innerHTML = loadingTemplate();

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

    if (options.playlistIds === '') {
        console.error('No playlist id(s) provided');
        return;
    };

    const playlistIds = options.playlistIds 
        .split(',')
        .map(id => id.trim());
    
    const [playlists] = await youtube.getPlaylists(playlistIds);

    // Get playlists from given ids and apply max length to descriptions
    const playlistsData = playlists
        .map(p => ({
            ...p, 
            description: p.description.length <= 0 
                ? '' 
                : p.description
                    .slice(0, options.descriptionMaxLength - 3)
                    .concat('...')
        }));
        
    await renderTemplate({
        element,
        templates, 
        templateId: options.templateId, 
        data: { items: playlistsData }
    });
    
    // Video embeds need to be re-rendered since this is asynchronous
    renderVideos();
}

const eclipsefdnVideoList = {
    render
};

export default eclipsefdnVideoList;
