using Services;
using LocalServices.Data;
using Models;
using System.Collections.Immutable;

namespace Services
{
    public class AccountOwnedRecipes : IAccountOwnedRecipesService
    {

        public Account Account { get; init; }

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

        public AccountOwnedRecipes(Account account, IDatabase 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);
        }
    }
}
