namespace inutralia.Views
{
    using inutralia.Models;
    using inutralia.ViewModels;
    using System;
    using System.Threading.Tasks;
    using Xamarin.Forms;

    public partial class RecipeListView : ContentPage
    {
        protected RecipeListViewModel ViewModel => BindingContext as RecipeListViewModel;

        protected bool firstTime = true;

        protected ModalFiltersRecipe filtersPage = null;

        public RecipeListView()
        {
            InitializeComponent();
            BindingContext = new RecipeListViewModel();
        }

        void ItemTapped(object sender, ItemTappedEventArgs e)
        {
            Navigation.PushAsync(
               new RecipeDetailView() { BindingContext = new RecipeViewModel(e.Item as Recipe) }
            );
        }

        public async Task ApplyFilters()
        {
            await Navigation.PopAsync();
            ViewModel.Recipes.Clear();
            ViewModel.RefreshRecipesCommand.Execute(BindingContext);
        }

        protected override async void OnAppearing()
        {
            base.OnAppearing();

            if (firstTime)
            {
                firstTime = false;
               // await DoFiltersAsync();
            }
        }

        private async void ToolbarFiltersClicked(object sender, EventArgs e)
        {
            if (ViewModel.IsNotBusy)
                await DoFiltersAsync();
        }

        protected async Task DoFiltersAsync()
        {
            if (filtersPage == null)
            {
                filtersPage = new ModalFiltersRecipe(this)
                {
                    BindingContext = ViewModel.Filters
                };
            }

            await Navigation.PushAsync(filtersPage);
        }
    }
}

