
namespace ShoopNCook.Pages;
using Models;
using ShoopNCook.Views;
using Services;

public partial class HomePage : ContentPage
{
    private readonly IRecipesService recipes;
    private readonly IAccountRecipesPreferencesService preferences;
    public HomePage(Account account, IEndpoint endpoint)
    {
		InitializeComponent();

        BindingContext = account.User;
        recipes = endpoint.RecipesService;
        preferences = recipes.GetPreferencesOf(account);


        void PushRecipe(Layout layout, RecipeInfo info)
        {
            layout.Children.Add(new RecipeView(info, () =>
            {
                Recipe recipe = recipes.GetRecipe(info);
                if (recipe != null)
                    Shell.Current.Navigation.PushAsync(new RecipePage(recipe, preferences, 1));
                else
                {
                    UserNotifier.Error("Could not find recipe");
                }
            }));
        }

        recipes.PopularRecipes().ForEach(recipe => PushRecipe(PopularsList, recipe));
        preferences.GetRecommendedRecipes().ForEach(recipe => PushRecipe(RecommendedList, recipe));
	}

    private async void OnSyncButtonClicked(object sender, EventArgs e)
    {
        string prompt = SearchPrompt.Text;
        if (string.IsNullOrEmpty(prompt))
            return;
        
        var searchPage = new SearchPage(recipes, preferences);
        await Shell.Current.Navigation.PushAsync(searchPage);
        searchPage.MakeSearch(SearchPrompt.Text);
    }
}