using BookReader.Services;
using BookReader.ViewModels;

namespace BookReader.Views;

public partial class BookshelfPage : ContentPage
{
    private readonly BookshelfViewModel _viewModel;

    public BookshelfPage(BookshelfViewModel viewModel)
    {
        InitializeComponent();
        _viewModel = viewModel;
        BindingContext = viewModel;
        SizeChanged += OnPageSizeChanged;
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
        UpdateGridSpan(Width);

        if (_viewModel.Books.Count == 0)
        {
            _ = _viewModel.LoadBooksCommand.ExecuteAsync(null);
        }
    }

    protected override async void OnNavigatedTo(NavigatedToEventArgs args)
    {
        base.OnNavigatedTo(args);

        if (_viewModel.Books.Count > 0 && !_viewModel.IsBusy)
        {
            await _viewModel.LoadBooksCommand.ExecuteAsync(null);
        }
    }

    private void OnPageSizeChanged(object? sender, EventArgs e)
    {
        UpdateGridSpan(Width);
    }

    private void UpdateGridSpan(double availableWidth)
    {
        if (availableWidth <= 0)
        {
            return;
        }

        var span = availableWidth switch
        {
            < 520 => 2,
            < 920 => 3,
            _ => 4
        };

        BooksGridLayout.Span = span;
    }
}
