using Models;
using ShoopNCook.Views;

namespace ShoopNCook.Pages;

public partial class CreateRecipePage : ContentPage
{

    private User owner;
    private Action<Recipe> onRecipeCreated;
    private IUserNotifier notifier;

	public CreateRecipePage(User owner, IUserNotifier notifier, Action<Recipe> onRecipeCreated)
	{
		InitializeComponent();
        this.owner = owner;
        this.onRecipeCreated = onRecipeCreated;
        this.notifier = notifier;
	}

    private void OnAddIngredientTapped(object sender, TappedEventArgs e)
    {
        IngredientList.Children.Add(new IngredientEntry());
    }

    private void OnAddStepTapped(object sender, TappedEventArgs e)
    {
        StepList.Children.Add(new StepEntry((uint) StepList.Children.Count() + 1));
    }
    private void OnBackButtonClicked(object sender, EventArgs e)
    {
        Navigation.PopAsync();
    }

    private void OnUploadRecipeClicked(object sender, EventArgs e)
    {

        uint callPerPers;
        uint cookTimeMins;
        bool hadErrors = false;

        if (!uint.TryParse(EnergyInput.Text, out callPerPers))
        {
            hadErrors = true;
            //TODO change EnergyInput background to red.
        }

        if (!uint.TryParse(CookTimeInput.Text, out cookTimeMins))
        {
            hadErrors = true;
            //TODO change CookTimeInput background to red.
        }

        if (hadErrors)
        {
            notifier.Error("You need to fix input errors before upload.");
            return;
        }

        RecipeBuilder builder = new RecipeBuilder(RecipeNameEntry.Text, owner)
            .SetCallPerPers(callPerPers)
            .SetCookTimeMins(cookTimeMins)
     //TODO .SetImage(RecipeImage)
            ;

        foreach (IngredientEntry entry in IngredientList.Children)
            builder.AddIngredient(entry.MakeValue());

        foreach (StepEntry entry in StepList.Children)
            builder.AddStep(entry.MakeStep());

        onRecipeCreated(builder.Build());
    }
}