using Endpoint;
using LocalEndpoint;
using Models;
using ShoopNCook.Views;

namespace ShoopNCook.Pages;

public partial class MyRecipesPage : ContentPage
{

    private IUserNotifier notifier;
    private IRecipesService service;
    private Account account;

	public MyRecipesPage(
            Account account,
            IRecipesService service,
            IUserNotifier notifier)
    {
        InitializeComponent();

        this.notifier = notifier;
        this.service = service;
        this.account = account;

        service
            .GetRecipesOf(account)
            .GetAccountRecipes()
            .ForEach(AddRecipeView);
    }

    private void AddRecipeView(RecipeInfo info)
    {
        RecipesLayout.Children.Add(new OwnedRecipeView(info, () =>
        {
            Recipe recipe = service.GetRecipe(info);
            IAccountRecipesPreferences preferences = service.GetPreferencesOf(account);
            Shell.Current.Navigation.PushAsync(new RecipePage(recipe, notifier, preferences, 1));
        },
            () => RemoveRecipe(info)
        ));
    }

    private void RemoveRecipe(RecipeInfo info)
    {
        IAccountOwnedRecipes recipes = service.GetRecipesOf(account);

        if (!recipes.RemoveRecipe(info))
        {
            notifier.Error("Could not remove recipe");
            return;
        }
        foreach (OwnedRecipeView view in RecipesLayout.Children)
        {
            if (view.IsViewing(info))
            {
                RecipesLayout.Remove(view);
                break;
            }
        }
        notifier.Success("Recipe successfully removed");
    }

    private void OnBackButtonClicked(object sender, EventArgs e)
    {
        Navigation.PopAsync();
    }
    private void OnAddRecipeButtonClicked(object sender, EventArgs e)
    {
        IAccountOwnedRecipes recipes = service.GetRecipesOf(account);

        var page = new CreateRecipePage(account.User, notifier, recipe =>
        {
            if (!recipes.UploadRecipe(recipe))
            {
                notifier.Error("Could not upload recipe.");
                return;
            }
            notifier.Success("Recipe Successfuly uploaded !");
            AddRecipeView(recipe.Info);
            Shell.Current.Navigation.PopAsync(); //go back to current recipe page.
        });
        Shell.Current.Navigation.PushAsync(page); //display RecipePage editor
    }
}