From 0df654df3cc388479dfe326d21c7ab309c73d6b8 Mon Sep 17 00:00:00 2001 From: Mei Chang van der Werff Date: Thu, 27 Nov 2025 21:12:28 +0100 Subject: [PATCH] Making unique name is now in addRecipe instead --- .../main/java/client/utils/ServerUtils.java | 56 ++++++++++--------- 1 file changed, 29 insertions(+), 27 deletions(-) diff --git a/client/src/main/java/client/utils/ServerUtils.java b/client/src/main/java/client/utils/ServerUtils.java index c87777c..bb7e6a6 100644 --- a/client/src/main/java/client/utils/ServerUtils.java +++ b/client/src/main/java/client/utils/ServerUtils.java @@ -65,14 +65,35 @@ public class ServerUtils { */ public Recipe addRecipe(Recipe newRecipe) throws IOException, InterruptedException { - String json = objectMapper.writeValueAsString(newRecipe); + //Make sure the name of the newRecipe is unque + List allRecipes = getRecipes(); - // TODO : check whether the name is unique, else add a number after it -// while(true){ -// if(){ -// System.out.println("Card name already exists pls enter a new one"); -// } -// } + boolean exists = allRecipes.stream() + .anyMatch(r -> r.getName().equals(newRecipe.getName())); + + + if(exists){ + int version = 1; + String newName; + + // Giving the "new" recipe a unique name + while (true) { + newName = newRecipe.getName() + "(" + version + ")"; + String finalNewName = newName; + boolean nameExists = allRecipes.stream() + .anyMatch(r -> r.getName().equals(finalNewName)); + + if (!nameExists){ + newRecipe.setName(newName); + break; + }else { + version++; + } + } + + } + + String json = objectMapper.writeValueAsString(newRecipe); //Recipe to backend @@ -121,31 +142,12 @@ public class ServerUtils { //200 is the status code for success, other codes can mean there is no recipe to clone if(response.statusCode() != statusOK){ - throw new IOException("No recipe to clone"); + throw new IOException("No recipe to clone"); } // recipe exists so you can make a "new" recipe aka the clone Recipe recipe = objectMapper.readValue(response.body(), Recipe.class); - List allRecipes = getRecipes(); - int version = 1; - String newName; - - // Giving the "new" recipe a unique name - while (true) { - newName = recipe.getName() + "(" + version + ")"; - String finalNewName = newName; - boolean exists = allRecipes.stream() - .anyMatch(r -> r.getName().equals(finalNewName)); - - if (!exists){ - break; - }else { - version++; - } - } - recipe.setId(null); // otherwise the id is the same as the original, and that's wrong - recipe.setName(newName); return addRecipe(recipe); }