using LocalEndpoint;
using LocalEndpoint.Data;
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 Database db;

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

            //Retrieve all owned recipes from database.
            db.ListAllRecipes().ForEach(recipe =>
            {
                if (recipe.Owner.Equals(account.User))
                    ownedRecipes.Add(recipe.Info.Id, recipe);
            });
        }

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

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

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


    }
}
