diff --git a/Francesco.Recipes.World/Services/Instruction/IInstructionService.cs b/Francesco.Recipes.World/Services/Instruction/IInstructionService.cs new file mode 100644 index 0000000..fa514a1 --- /dev/null +++ b/Francesco.Recipes.World/Services/Instruction/IInstructionService.cs @@ -0,0 +1,9 @@ +namespace Francesco.Recipes.World.Services.Instruction +{ + public interface IInstructionService + { + Task MoveInstructionUpAsync(Guid instructionId); + + Task MoveInstructionDownAsync(Guid instructionId); + } +} diff --git a/Francesco.Recipes.World/Services/Instruction/InstructionService.cs b/Francesco.Recipes.World/Services/Instruction/InstructionService.cs new file mode 100644 index 0000000..5015426 --- /dev/null +++ b/Francesco.Recipes.World/Services/Instruction/InstructionService.cs @@ -0,0 +1,54 @@ +using Francesco.Recipes.World.Repositories.Instruction; + +namespace Francesco.Recipes.World.Services.Instruction +{ + public class InstructionService : IInstructionService + { + private readonly IInstructionRepository _instructionRepository; + + public InstructionService(IInstructionRepository instructionRepository) + { + _instructionRepository = instructionRepository; + } + + public async Task MoveInstructionDownAsync(Guid instructionId) + { + var instruction = await _instructionRepository.GetInstructionWithRecipeAsync(instructionId); + + var instructions = await _instructionRepository.GetInstructionsByRecipeIdAsync(instruction.Recipe.Id); + + var maxStep = instructions.Max(i => i.Number); + + if (instruction.Number >= maxStep) + { + return; + } + + var neighbor = instructions.FirstOrDefault(i => i.Number == instruction.Number + 1); + + if (neighbor != null) + { + await _instructionRepository.SwapInstructionOrderAsync(instruction, neighbor); + } + } + + public async Task MoveInstructionUpAsync(Guid instructionId) + { + var instruction = await _instructionRepository.GetInstructionWithRecipeAsync(instructionId); + + if (instruction.Number == 1) + { + return; + } + + var instructions = await _instructionRepository.GetInstructionsByRecipeIdAsync(instruction.Recipe.Id); + + var neighbor = instructions.FirstOrDefault(i => i.Number == instruction.Number - 1); + + if (neighbor != null) + { + await _instructionRepository.SwapInstructionOrderAsync(instruction, neighbor); + } + } + } +}