using MauiAppStock.Models;
using MauiAppStock.ViewModels;

namespace MauiAppStock.Views
{
    public partial class AppareilPiecesPage : ContentPage
    {
        private Appareil _appareil;

        public AppareilPiecesPage(Appareil appareil)
        {
            InitializeComponent();
            _appareil = appareil;
            BindingContext = new AppareilPiecesViewModel(_appareil);
        }
        
        protected override void OnAppearing()
        {
            base.OnAppearing();
            var vm = BindingContext as AppareilPiecesViewModel;
            vm?.LoadAssociationsCommand.Execute(null);
        }

        private async void OnAssociationTapped(object sender, ItemTappedEventArgs e)
        {
            if (e.Item is AppareilPiece assoc)
            {
                await Navigation.PushAsync(new EditAssociationPage(assoc));
            }
        }

        private async void OnAddPieceClicked(object sender, EventArgs e)
        {
            await Navigation.PushAsync(new AddAppareilPiecePage(_appareil));
        }

        private void OnToggleSortOrderClicked(object sender, EventArgs e)
        {
            var vm = BindingContext as AppareilPiecesViewModel;
            if (vm != null)
            {
                vm.IsAscending = !vm.IsAscending;
            }
        }
    }
}