using Endpoint;
using Models;
using System.Collections.Immutable;

namespace LocalEndpoint
{
    internal class RecipesService : IRecipesService
    {

        private readonly RecipesDatabase db;
        private readonly Dictionary<Account, AccountData> accountsData = new Dictionary<Account, AccountData>();

        public RecipesService(RecipesDatabase db)
        {
            this.db = db;
        }

        public ImmutableList<RecipeInfo> PopularRecipes()
        {
            return db.ListAll().Take(4).ToImmutableList().ConvertAll(v => v.Info);
        }

        public Recipe GetRecipe(RecipeInfo info)
        {
            return db.Get(info.Id);
        }


        public IAccountOwnedRecipes GetRecipesOf(Account account)
        {
            return GetOrInitData(account).Recipes;
        }
        public IAccountRecipesPreferences GetPreferencesOf(Account account)
        {
            return GetOrInitData(account).Preferences;
        }

        private AccountData GetOrInitData(Account account)
        {
            AccountData? data;
            accountsData.TryGetValue(account, out data);

            if (data == null)
            {
                AccountOwnedRecipes recipes = new AccountOwnedRecipes(account, db);
                recipes.UploadRecipe(new Recipe(new RecipeInfo("Cupcake", 500, 12, new Uri("https://www.mycake.fr/wp-content/uploads/2015/12/rs_cupcake_4x3.jpg"), 4.2F, Guid.NewGuid()), account.User, new List<Ingredient> { new Ingredient("Chocolate", 4) }.ToImmutableList(), new List<PreparationStep> { new PreparationStep("Eat Chocolate", "Eat the chocolate") }.ToImmutableList()));
                AccountRecipesPreferences preferences = new AccountRecipesPreferences(account, db);
                data = new AccountData(recipes, preferences);
                accountsData.Add(account, data);
            }
            return data;
        }

    }
}
