using Model;
using System.Collections.ObjectModel;

namespace Linaris;

public partial class PlaylistsPage : ContentPage
{
    private ObservableCollection<Playlist> playlists = (Application.Current as App).Manager.GetPlaylists();

    public ObservableCollection<Playlist> Playlists { get => playlists; }

    public PlaylistsPage()
	{
		InitializeComponent();
        BindingContext = this;
    }

    // Reset methods

    void ResetAll(object sender, EventArgs e)
    {
        ResetSubMenus(sender, e);
    }

    void ResetSubMenus(object sender, EventArgs e)
    {
        foreach (var Playlist in playlists)
        {
            Playlist.IsSubMenuVisible = false;
        }
    }


    // Add methods

    async void AddPlaylist(object sender, EventArgs e)
    {
        await Navigation.PushModalAsync(new AddPlaylistPage());
    }


    // Remove methods

    void RemovePlaylist(object sender, EventArgs e)
    {
        if (sender is Button button)
        {
            if (button.BindingContext is Playlist playlist)
            {
                playlists.Remove(playlist);
            }
        }
    }


    // Show methods

    void ShowSubMenu(object sender, EventArgs e)
    {
        if (sender is Image image)
        {
            if (image.BindingContext is Playlist playlist)
            {
                if (!playlist.IsSubMenuVisible)
                {
                    ResetAll(sender, e);
                    playlist.IsSubMenuVisible = true;
                }
                else
                {
                    ResetSubMenus(sender, e);
                }
            }
        }
    }


    // Change methods

    private async void ChangeImage(object sender, EventArgs e)
    {
        var result = await FilePicker.PickAsync(new PickOptions
        {
            PickerTitle = "Choisissez une nouvelle image !",
            FileTypes = FilePickerFileType.Images
        });

        if (result == null)
        {
            return;
        }

        if (sender is Button button)
        {
            if (button.BindingContext is Playlist playlist)
            {
                playlist.ImageURL = result.FullPath;
            }
        }
    }

    // Navigation

    async void GoToPlaylist(object sender, EventArgs e)
    {
        if (sender is Button button)
        {
            if (button.BindingContext is Playlist playlist)
            {
                (Application.Current as App).Manager.CurrentPlaylist = playlist;
            }
        }
        await Navigation.PushAsync(new PlaylistPage());
    }
}