Basic print functionality done with comments

This commit is contained in:
Rithvik Sriram 2025-12-05 13:54:56 +01:00
commit 91fbefb392

View file

@ -1,4 +1,67 @@
package client.utils; package client.utils;
import commons.Recipe;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class PrintExportService { public class PrintExportService {
/**
* Builds the String with all the recipe data in a human-readable format and returns said string
* @param recipe - Recipe Object that needs to be converted
* @return - String Result that is the converted recipe object
*/
public static String buildRecipeText(Recipe recipe){
String result = "Title: " + recipe.getName() + "\nRecipe ID: " + recipe.getId() + "\n" +
"Ingredients: "; //Starts the string with name and recipe ID
for(int i =0; i<recipe.getIngredients().size();i++){ // For loop adding ingredients one by one
result += recipe.getIngredients().get(i) + ", ";
} }
result += "Steps:\n";
for(int i =0; i<recipe.getPreparationSteps().size();i++){ // Preparation Steps separated by new lines
result += (i+1) + ": " + recipe.getPreparationSteps().get(i) + "\n";
}
return result;
}
/**
* Method that checks if the directory path of the selected directory is valid and throws and error
* if not valid
* @param path - Path to directory
*/
public static void validateFolder(Path path){
if (path == null) { //Null path value
throw new IllegalArgumentException("Path is empty");
}
if(!Files.exists(path)){ //If Folder doesn't exist
throw new IllegalArgumentException("Folder does not exist");
}
if(!Files.isDirectory(path)){ // If folder is not directory
throw new IllegalArgumentException("Given path is not a folder");
}
}
/**
* Method that exports a plain-text String of recipe data, into a newly created file from
* a selected directory provided as a path to the method and names said file based on the
* nameOfFile param
* @param recipeData - String containing recipe data that will be written to file
* @param dirFilePath - Path to Folder
* @param nameOfFile - Name of file to be created
*/
public static void exportToFile(String recipeData, Path dirFilePath, String nameOfFile){
validateFolder(dirFilePath); //runs validate Folder method to check if Directory path is valid
Path filePath = dirFilePath.resolve(nameOfFile); //Creates a file with name provided in directory and stores path in PATH object
try {
Files.writeString(filePath, recipeData); // Writes the recipe data into the File.
}
catch (IOException e){
System.err.println("An error occurred while writing to the file");
}
}
}