
import AppData from "../../../Common/AppData";
import SoundUI from "./SoundUI";
import Utils from "../../../Utils/Utils";
import EventBus, { Events, Event } from "../../../Events/EventBus";
import PlaylistUtils from "../../../Utils/PlaylistUtils";
import Player from "../../../BackgroundJobs/Player";

class SoundsUI {


    _componentUI = null;
    _soundsCollections = null;
    _soundUIInstances = [];
    _selectedSounds = [];
    _options = {};

    constructor(options = {}) {
        this._options = options;
        this._soundsCollections = AppData.getInstance().get('sounds_collections');
        if (!this._soundsCollections) {
            console.error('No sounds data available');
            alert('No sounds data available');
            return;
        }
        this._soundUIInstances = [];
        this._buildSoundsList();
    }

    _buildSoundsList() {
        if (!this._soundsCollections || this._soundsCollections.length === 0) {
            console.error('No sounds data available to build the list');
            return;
        }

        const html = `
            <div class="sounds-list"></div>
        `;
        this._componentUI = jQuery(html);

        const sound_pro_badge = AppData.getInstance().getLabel('sound_pro_badge');
        const sound_require_login_badge = AppData.getInstance().getLabel('sound_require_login_badge');

        const show_playlist_names = AppData.getInstance().get('show_playlist_names');

        this._soundsCollections.forEach(collection => {

            const collectionUI = jQuery(`<div class="flex flex-wrap gap-4 max-w-screen-lg justify-start sounds-category">
                </div>`);

            if (show_playlist_names === 'on') {
                const { playlist_name } = collection;
                const collectionNameUI = jQuery(`
                    <div class="font-semibold playlist_name">
                    ${playlist_name}
                    </div>
                    `);
                collectionNameUI.appendTo(this._componentUI);
            }

            const { sounds } = collection;
            sounds.forEach(sound => {
                const { soundName, soundIconUrl } = sound;
                const soundUI = jQuery(`
                    <div class="w-1/3 sm:w-1/4 md:w-1/5 p-5 relative sound-ui">
                        <div class="text-sm font-semibold absolute right-2 top-0 text-green-600 bg-white/80 rounded-full px-2 py-0.5 cursor-pointer hidden pro-sound">${sound_pro_badge}</div>
                        <div class="text-sm font-semibold absolute right-2 top-0 text-orange-500 bg-white/80 rounded-full px-2 py-0.5 cursor-pointer hidden login-sound">${sound_require_login_badge}</div>

                        <div class="flex items-center justify-center">
                            <div class="playlist-img-ui inactive-sound-opacity">
                                <img src="${soundIconUrl}" alt="">
                            </div>
                        </div>
                        <div class="flex items-center justify-center mt-2 cursor-pointer sound-name">
                            <div>${soundName}</div>
                        </div>
                        <div class="volume-slider-ui">
                            <div class="mt-9 m-auto volume-slider" style="opacity: 0;">
                                <div class="handle"></div>
                            </div>
                        </div>
                    </div>
                `);
                soundUI.appendTo(collectionUI);
                collectionUI.appendTo(this._componentUI);
                const sI = new SoundUI(soundUI, sound, (payload) => this._onPlayPauseChange(payload))
                this._soundUIInstances.push(sI);
            });
        });
        this._handleEditPlaylist();
    }

    async _handleEditPlaylist() {
        if (this._options.existingPlaylistId) {
            const playlists = await PlaylistUtils.getSanitizedPlaylists();
            if (!Array.isArray(playlists)) {
                return;
            }
            const foundPlaylist = playlists.find(playlist => playlist.id === this._options.existingPlaylistId);
            if (foundPlaylist) {

                if (Utils.isFunction(this._options?.onExistingPlaylistData)) {
                    this._options.onExistingPlaylistData(foundPlaylist);
                }

                Player.getInstance().setPlaylistId(foundPlaylist?.id);

                const { sounds } = foundPlaylist;
                for (const soundInstance of this._soundUIInstances) {
                    const { id } = soundInstance.getSoundInfo();
                    const playlistSound = sounds.find(snd => snd.id === id);
                    if (playlistSound) {
                        const { soundVolume } = playlistSound;
                        setTimeout(() => {
                            soundInstance.setStatus(true);
                            soundInstance.setVolume(Number(soundVolume));
                        }, 50)
                    }
                }
            }
        }
    }

    _onPlayPauseChange(payload) {
        if (Utils.isFunction(this._options?.onSelectedSounds)) {
            this._options?.onSelectedSounds();
        }
    }

    getComponentUI() {
        return this._componentUI;
    }

    stopAll() {
        for (const soundInstance of this._soundUIInstances) {
            soundInstance.pauseSilent();
        }
    }

    destroyUI() {
        this._componentUI.remove();
    }
}

export default SoundsUI;