From 9b5cefb4c06539f8172394ba2e42a0e6d73f71df Mon Sep 17 00:00:00 2001
From: HSoreide <sofie.scisly@gmail.com>
Date: Sat, 15 Apr 2023 21:00:06 +0200
Subject: [PATCH] FileHandler writes and reads ingredients at hand from file

---
 .../demo/data/recipes/FileHandler.java        | 89 +++++++++++++------
 .../demo/data/recipes/FileHandlerTest.java    | 21 +++++
 2 files changed, 81 insertions(+), 29 deletions(-)

diff --git a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FileHandler.java b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FileHandler.java
index 5d8f0989..2cd7667d 100644
--- a/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FileHandler.java
+++ b/src/main/java/no/ntnu/idatt1002/demo/data/recipes/FileHandler.java
@@ -1,37 +1,24 @@
 package no.ntnu.idatt1002.demo.data.recipes;
 
-import no.ntnu.idatt1002.demo.data.Economics.*;
-
 import java.io.*;
-import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.List;
 import java.util.Scanner;
-import java.nio.file.FileSystems;
-import java.time.LocalDate;
 
+//TODO: Refactor to make use of generics, which requires
+// refactoring of more classes and write mor eunit tests and JavaDoc.
 public class FileHandler {
 
-
-   // private static final String filePath = FileSystems.getDefault().getPath("src", "main", "resources", "recipes").toString();
     private static final String fileType = ".register";
     private static final String registerName = "RecipeRegister";
-
-
     private static final String filePath = "src/main/resources/recipes/";
- /*   private static final String date = "date=";
-    private static final String description = "description=";
-    private static final String amount = "amount=";
-    private static final String isRecurring = "isRecurring=";
-    private static final String category = "category=";*/
 
 
     public static void writeRegister(RecipeRegister recipeRegister, String title) {
-        if(recipeRegister == null) {
+        if (recipeRegister == null) {
             throw new IllegalArgumentException("Only a valid register object can be written to file.");
         }
 
-        try( FileWriter fileWriter = new FileWriter(filePath + title + fileType);) {
+        try (FileWriter fileWriter = new FileWriter(filePath + title + fileType);) {
             recipeRegister.getRecipes().forEach((recipe) ->
                     {
                         try {
@@ -42,7 +29,7 @@ public class FileHandler {
                     }
             );
 
-        } catch ( IOException e ) {
+        } catch (IOException e) {
             e.printStackTrace();
         }
     }
@@ -52,17 +39,17 @@ public class FileHandler {
         sb.append("# ")
                 .append(recipe.getName())
                 .append("\n")
-                .append(formatIngredientList(recipe))
+                .append(formatIngredientList(recipe.getIngredientList()))
                 .append("\n")
                 .append(recipe.getInstructions())
                 .append("\n\n");
         return sb;
     }
 
-    public static StringBuilder formatIngredientList(Recipe recipe) {
+    public static StringBuilder formatIngredientList(List<RecipeIngredient> ingredientList) {
         StringBuilder sb = new StringBuilder();
 
-        recipe.getIngredientList().forEach((ingredient) -> {
+        ingredientList.forEach((ingredient) -> {
             sb.append("- ")
                     .append(ingredient.getFoodType())
                     .append(" | ")
@@ -80,14 +67,12 @@ public class FileHandler {
     public static void readToTerminal(String title) throws FileNotFoundException {
         File file = new File(filePath + title + fileType);
         Scanner sc = new Scanner(file);
-        while(sc.hasNext()) {
+        while (sc.hasNext()) {
             System.out.println(sc.nextLine());
         }
     }
 
 
-
-
     public static RecipeRegister readRecipeRegister(String title) throws FileNotFoundException {
         File file = new File(filePath + title + fileType);
 
@@ -99,11 +84,11 @@ public class FileHandler {
 
             while (sc.hasNext()) {
                 line = sc.next();
-                if(!line.isBlank()) {
+                if (!line.isBlank()) {
                     register.addRecipe(readRecipe(line));
                 }
             }
-        }catch(FileNotFoundException e) {
+        } catch (FileNotFoundException e) {
             System.out.println("The file was not found.");
             return null;
         }
@@ -127,7 +112,7 @@ public class FileHandler {
         while (sc.hasNextLine()) {
             line = sc.nextLine();
 
-            if(line.startsWith("-")) {
+            if (line.startsWith("-")) {
                 String[] ingredientParts = line.split("\\|");
 
                 FoodItem ingredientType = FoodItem.valueOf(ingredientParts[0].replaceFirst("-", "").strip());
@@ -137,7 +122,7 @@ public class FileHandler {
                 recipe.addIngredient(ingredientType, ingredientAmount, ingredientUnit);
 
             } else {
-                if(!line.isBlank()) {
+                if (!line.isBlank()) {
                     sb.append(line).append("\n");
                 }
             }
@@ -146,4 +131,50 @@ public class FileHandler {
 
         return recipe;
     }
-}
+
+
+    // ================  Ingredients at hand ===============================
+
+    public static void writeIngredientsAtHand(IngredientsAtHand ingredientsAtHand, String title) throws IOException {
+        if (ingredientsAtHand == null) {
+            throw new IllegalArgumentException("Only a valid register object can be written to file.");
+        }
+
+        StringBuilder sb = new StringBuilder();
+
+        try (FileWriter fileWriter = new FileWriter(filePath + title + fileType);) {
+            ingredientsAtHand.getIngredientsAtHand().forEach((ingredient) -> {
+                sb.append(ingredient).append("\n");
+
+            });
+            try {
+                fileWriter.write(String.valueOf(sb));
+            } catch (IOException e) {
+                throw new RuntimeException(e);
+            }
+        }
+    }
+
+
+    public static IngredientsAtHand readIngredientsAtHand(String title) {
+        File file = new File(filePath + title + fileType);
+
+        IngredientsAtHand ingredientsAtHand = new IngredientsAtHand();
+
+        try (Scanner sc = new Scanner(file)) {
+            String line;
+
+            while (sc.hasNext()) {
+                line = sc.next();
+                if (!line.isBlank()) {
+                   ingredientsAtHand.addIngredient(FoodItem.valueOf(line));
+                }
+            }
+        } catch (FileNotFoundException e) {
+            System.out.println("The file was not found.");
+            return null;
+        }
+
+        return ingredientsAtHand;
+    }
+}
\ No newline at end of file
diff --git a/src/test/java/no/ntnu/idatt1002/demo/data/recipes/FileHandlerTest.java b/src/test/java/no/ntnu/idatt1002/demo/data/recipes/FileHandlerTest.java
index bb6dc460..9e3ad51f 100644
--- a/src/test/java/no/ntnu/idatt1002/demo/data/recipes/FileHandlerTest.java
+++ b/src/test/java/no/ntnu/idatt1002/demo/data/recipes/FileHandlerTest.java
@@ -5,12 +5,15 @@ import org.junit.jupiter.api.DisplayName;
 import org.junit.jupiter.api.Test;
 
 import java.io.FileNotFoundException;
+import java.io.FileWriter;
+import java.io.IOException;
 
 import static org.junit.jupiter.api.Assertions.*;
 
 class FileHandlerTest {
 
     RecipeRegister recipeRegister = new RecipeRegister();
+    IngredientsAtHand ingredientsAtHand = new IngredientsAtHand();
 
     Recipe recipe1;
     Recipe recipe2;
@@ -32,6 +35,14 @@ class FileHandlerTest {
         recipeRegister.addRecipe(recipe1);
         recipeRegister.addRecipe(recipe2);
 
+        // For AtHand:
+
+        ingredientsAtHand.addIngredient(FoodItem.POTATO);
+        ingredientsAtHand.addIngredient(FoodItem.MILK);
+        ingredientsAtHand.addIngredient(FoodItem.LEMON);
+        ingredientsAtHand.addIngredient(FoodItem.MINCED_MEAT);
+
+
     }
 
 
@@ -64,5 +75,15 @@ class FileHandlerTest {
     }
 
 
+    // Ingredients at hand nesting
+
+
+    @Test
+    @DisplayName("Write ingredients at hand to file.")
+    void writeIngredientsAtHandToFile() throws FileNotFoundException {
+        assertAll(() -> FileHandler.writeIngredientsAtHand(ingredientsAtHand, "AtHandRegister"));
+        FileHandler.readToTerminal("AtHandRegister");
+    }
+
 
 }
\ No newline at end of file
-- 
GitLab