import { fetchData } from "./Fetch";
import AppData from "../Common/AppData";

class PlaylistUtils {

    static async getSanitizedPlaylists() {

        const result = await fetchData('playlists', 'GET', {}, true, true, true);

        if (result?.status === 200) {
            
            let allSounds = [];
            const soundsCollections = AppData.getInstance().get('sounds_collections');
            if (Array.isArray(soundsCollections)) {
                allSounds = soundsCollections.flatMap(playlist => playlist.sounds);
            }

            const { playlists } = result?.data || [];

            const soundMap = new Map();
            allSounds.forEach(sound => {
                soundMap.set(sound.id, sound);
            });

            const sanitizedPlaylists = playlists.map(playlist => {
                const sanitizedSounds = playlist.sounds
                    .map(s => {
                        const matchedSound = soundMap.get(Number(s.id));
                        if (!matchedSound) return null;

                        return {
                            ...matchedSound,
                            soundVolume: s.soundVolume
                        };
                    })
                    .filter(Boolean);

                return {
                    ...playlist,
                    sounds: sanitizedSounds
                };
            });

            return sanitizedPlaylists;
        } else {
            console.warn('MyPlaylistsHandler__getPlaylists', result);
        }

        return [];
    }

}

export default PlaylistUtils;