From 71ebfcf4bee42b279c74490aaa4d86b96544ca1a Mon Sep 17 00:00:00 2001 From: franc Date: Tue, 15 Apr 2025 16:11:07 +0200 Subject: [PATCH] Implement the Sorting Logic --- .../Instruction/IInstructionService.cs | 9 ++++ .../Instruction/InstructionService.cs | 54 +++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 Francesco.Recipes.World/Services/Instruction/IInstructionService.cs create mode 100644 Francesco.Recipes.World/Services/Instruction/InstructionService.cs 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); + } + } + } +}