using API.DBAccess; using API.Models.RecipeModels; using Microsoft.AspNetCore.Mvc; namespace API.BusinessLogic { public class RecipeLogic { private readonly RecipeDBAccess _dbAccess; public RecipeLogic(RecipeDBAccess dbAccess) { _dbAccess = dbAccess; } /// /// Gets all the recipes from _dbaccess and checks if there are any /// /// /// public async Task GetRecipes(int userId) { var recipes = await _dbAccess.ReadRecipes(userId); if (recipes == null || recipes.Count == 0) { return new ConflictObjectResult(new { message = "Could not find any recipes" }); } return new OkObjectResult(recipes); } // public async Task GetRecipe(int recipeId) { var recipe = await _dbAccess.ReadRecipe(recipeId); if (recipe == null || recipe.Id == 0) { return new ConflictObjectResult(new { message = "Could not find any recipe" }); } return new OkObjectResult(recipe); } public async Task CreateRecipe(RecipeDTO recipe, int userId) { var recipes = await _dbAccess.ReadRecipes(userId); foreach (var item in recipes) { if (item.Name == recipe.Name) { return new ConflictObjectResult(new { message = "Recipe name is already in use." }); } } Recipe dish = new Recipe(); dish.Name = recipe.Name; dish.Description = recipe.Description; dish.Ingredients = new List(); dish.Directions = new List(); foreach (var item in recipe.Ingredients) { Ingredient ingredient = new Ingredient(); ingredient.Unit = item.Unit; ingredient.Name = item.Name; ingredient.Amount = item.Amount; dish.Ingredients.Add(ingredient); } foreach (var item in recipe.Directions) { Directions directions = new Directions(); directions.Instruktions = item.Instructions; dish.Directions.Add(directions); } return await _dbAccess.CreateRecipe(dish, userId); } public async Task EditRecipe(RecipeDTO recipe, int recipeId, int userId) { var recipes = await _dbAccess.ReadRecipes(userId); var dish = await _dbAccess.ReadRecipe(recipeId); foreach (var item in recipes) { if (item.Name == recipe.Name) { return new ConflictObjectResult(new { message = "Recipe name is already in use." }); } } dish.Name = recipe.Name; dish.Description = recipe.Description; dish.Directions = new List(); foreach (var item in recipe.Ingredients) { Ingredient ingredient = new Ingredient(); ingredient.Unit = item.Unit; ingredient.Name = item.Name; ingredient.Amount = item.Amount; dish.Ingredients.Add(ingredient); } foreach (var item in recipe.Directions) { Directions directions = new Directions(); directions.Instruktions = item.Instructions; dish.Directions.Add(directions); } return await _dbAccess.UpdateRecipe(dish); } public async Task DeleteRecipe(int recipeId) { var recipe = await _dbAccess.ReadRecipe(recipeId); if (recipe != null) { return await _dbAccess.DeleteUser(recipe); } return new ConflictObjectResult(new { message = "Invalid user" }); } } }