/*
 * 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 'isomorphic-fetch';

const apiBasePath = 'https://api.eclipse.org/media';

export const playlistMapping = p => {
    return {
        id: p.id,
        title: p.snippet.title,
        description: p.snippet.description,
        publishedAt: p.snippet.published_at,
        thumbnails: p.snippet.thumbnails,
        channelId: p.snippet.channel_id,
        channelTitle: p.snippet.channel_title,
        player: {
            embedHtml: p.player.embed_html
        }
    }
}

const getPlaylistsFromChannel = async (channelName) => {
    try {
        if (!channelName) throw Error(`No channel name was given to retrieve playlists`);

        const response = await fetch(`${apiBasePath}/youtube/playlists?channel=${channelName}`);
        const data = await response.json();
        const playlists = data.map(playlistMapping);

        if (!response.ok) throw Error(`Could not fetch playlists for channel named ${channelName}`)

        return [playlists, null];
    } catch (error) {
        return [null, error];
    }
}

const getPlaylist = async (playlistId) => {
    try {
        if (!playlistId) throw Error('No playlist id was given');

        const response = await fetch(`${apiBasePath}/youtube/playlists/${playlistId}`);
        const data = await response.json();
        const playlist = playlistMapping(data);

        if (!response.ok) throw Error(`Could not fetch playlist using playlist id ${playlistId}`);

        return [playlist, null];
    } catch (error) {
        return [null, error];
    }
}

const getPlaylists = async (playlistIds = []) => {
    try {
        if (playlistIds.length === 0) throw Error('No playlist ids were provided');

        const responses = await playlistIds
            .reduce(async (accumulator, id) => {
                const [playlist, error] = await getPlaylist(id);

                // Add playlist to playlists array in accumulator
                (await accumulator)[0].push(playlist);
                // Add error to errors array in accumulator
                (await accumulator)[1].push(error);

                return accumulator;
            }, [[], []])

            return responses;
    } catch (error) {
        return [null, error];
    }
}

export const youtube = {
    getPlaylistsFromChannel,
    getPlaylist,
    getPlaylists
}
