using PaklenaBasta.MAUI.Models;
using PaklenaBasta.MAUI.Services;

namespace PaklenaBasta.MAUI.Views;

public partial class HomePage : ContentPage
{
    private readonly ApiService _api;
    public HomePage(ApiService api)
    {
        InitializeComponent();
        _api = api;
        Loaded += HomePage_Loaded;
    }

    private async void HomePage_Loaded(object sender, EventArgs e)
    {
        await LoadFilmsAsync();
    }

    private async Task LoadFilmsAsync()
    {
        var films = await _api.GetFilmsAsync();
        if (films != null)
            FilmsCollection.ItemsSource = films;
    }

    private async void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.CurrentSelection.FirstOrDefault() is FilmDto film)
        {
            // get stream URL
            var stream = await _api.GetStreamAsync(film.Id);
            if (stream != null)
            {
                await Navigation.PushAsync(new PlayerPage(stream.Url));
            }
        }
    }
}
