using Models;
using Services;
using ShoopNCook.Views;
using System.Collections.ObjectModel;

namespace ShoopNCook.Pages;
public partial class SearchPage : ContentPage
{
    private readonly IRecipesService recipesService;
    private readonly IAccountRecipesPreferencesService preferences;

    public ObservableCollection<RecipeView> FoundRecipes { get; private init; } = new ObservableCollection<RecipeView>();

    public SearchPage(IRecipesService recipes, IAccountRecipesPreferencesService preferences)
	{
        BindingContext = this;
        this.recipesService = recipes;
        this.preferences = preferences;
        InitializeComponent();
    }

    public void MakeSearch(string prompt)
    {
        if (string.IsNullOrEmpty(prompt))
        {
            return;
        }
        SearchPrompt.Text = prompt;
        FoundRecipes.Clear();
        foreach (RecipeInfo info in recipesService.SearchRecipes(prompt))
        {
            FoundRecipes.Add(new RecipeView(info, () =>
            {
                Recipe recipe = recipesService.GetRecipe(info);
                if (recipe != null)
                    Shell.Current.Navigation.PushAsync(new RecipePage(recipe, preferences, 1));
                else
                    UserNotifier.Error("Could not find recipe");
            }));
        }
    }

    private async void OnBackButtonClicked(object sender, EventArgs e)
    {
        await Navigation.PopAsync();
    }

    private void OnSearchClicked(object sender, EventArgs e)
    {
        MakeSearch(SearchPrompt.Text);
    }
}