using LocalEndpoint;
using Models;
using System.Collections.Immutable;

namespace Endpoint
{
    internal class AccountOwnedRecipes : IAccountOwnedRecipes
    {

        public Account Account { get; init; }

        private readonly Dictionary<Guid, Recipe> ownedRecipes = new Dictionary<Guid, Recipe>();
        private readonly RecipesDatabase db;

        public AccountOwnedRecipes(Account account, RecipesDatabase db)
        {
            Account = account;
            this.db = db;

            //Retrieve all owned recipes from database.
            db.ListAll().ForEach(recipe =>
            {
                if (recipe.Owner == account.User) ownedRecipes[recipe.Info.Id] = recipe;
            });
        }

        public bool UploadRecipe(Recipe recipe)
        {
            Guid id = recipe.Info.Id;
            if (ownedRecipes.ContainsKey(id))
            {
                return false;
            }
            db.Insert(recipe);
            ownedRecipes.Add(id, recipe);
            return true;
        }

        public bool RemoveRecipe(RecipeInfo info)
        {
            db.Remove(info.Id);
            return ownedRecipes.Remove(info.Id);
        }

        public ImmutableList<RecipeInfo> GetAccountRecipes()
        {
            return ownedRecipes.Values.ToImmutableList().ConvertAll(r => r.Info);
        }


    }
}
