Skip to content

Commit

Permalink
Merge pull request #105 from AY2324S1-CS2113-F11-1/meal_
Browse files Browse the repository at this point in the history
fix missing
  • Loading branch information
MrOPPA1 committed Nov 14, 2023
2 parents 0936716 + 999f916 commit 85c86ab
Show file tree
Hide file tree
Showing 7 changed files with 220 additions and 20 deletions.
18 changes: 18 additions & 0 deletions src/main/java/seedu/duke/Duke.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
package seedu.duke;

import java.util.ArrayList;

import seedu.duke.commands.Command;
import seedu.duke.commands.CommandResult;
import seedu.duke.commands.ExitCommand;
import seedu.duke.commands.meal.MealCommand;
import seedu.duke.goal.GoalList;
import seedu.duke.meal.Meal;
import seedu.duke.parser.Parser;
import seedu.duke.exerciselog.Log;
import seedu.duke.storagefile.AchmStorage;
import seedu.duke.storagefile.DataManager;
import seedu.duke.storagefile.GoalStorage;
import seedu.duke.ui.TextUi;
import seedu.duke.storagefile.ExerciseLogStorage;
Expand All @@ -33,6 +38,7 @@ public class Duke {
private final String goalFilePath = "./data/GoalRecord.txt";
private final String achmFilePath = "./data/Achievement.txt";
private final String mealSavePath = "Meal.json";
private static ArrayList<Meal> meals = new ArrayList<Meal>();

public static void main(String... launchArgs) {
new Duke().run(launchArgs);
Expand Down Expand Up @@ -64,6 +70,13 @@ private void start(String[] launchArgs) {
achmStorage = AchmStorage.initializeGoalStorage(dirPath, achmFilePath);
achmStorage.restoreGoalRecord();
ui.showWelcomeMessage(VERSION, "storage.getPath()");
DataManager.setRelativePath(mealSavePath);
String dataJson = DataManager.readData();
ArrayList<Meal> data = DataManager.convertFromJsonToMealList(dataJson);
if (data != null) {
meals = data;
}
MealCommand.setMeals(meals);
} catch (Exception e) { // TODO: change to specific storage exceptions later
ui.showInitFailedMessage();
throw new RuntimeException(e);
Expand All @@ -75,6 +88,11 @@ private void start(String[] launchArgs) {
*/
private void exit() {
ui.showGoodbyeMessage();
try {
DataManager.saveData(DataManager.convertToJson(meals));
} catch (Exception exception) {
ui.showToUser(exception.toString());
}
System.exit(0);
}

Expand Down
25 changes: 13 additions & 12 deletions src/main/java/seedu/duke/commands/HelpCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import seedu.duke.commands.logcommands.ViewLogCommand;
import seedu.duke.commands.logcommands.UpdateLogCommand;
import seedu.duke.commands.logcommands.DeleteLogCommand;
import seedu.duke.commands.meal.*;

/**
* Shows help instructions.
Expand All @@ -22,17 +23,17 @@ public CommandResult execute() {

return new CommandResult(
helpMsg
+ "\n" + LogCommand.MESSAGE_USAGE
+ "\n" + DeleteLogCommand.MESSAGE_USAGE
+ "\n" + UpdateLogCommand.MESSAGE_USAGE
+ "\n" + ViewLogCommand.MESSAGE_USAGE
+ "\n" + DeleteLogCommand.MESSAGE_USAGE
+ "\n" + GoalCommand.MESSAGE_USAGE
+ "\n" + ViewGoalCommand.MESSAGE_USAGE
+ "\n" + DeleteGoalCommand.MESSAGE_USAGE
+ "\n" + AchieveGoalCommand.MESSAGE_USAGE
+ "\n" + AchievementCommand.MESSAGE_USAGE
+ "\n" + ExitCommand.MESSAGE_USAGE
);
+ "\n" + LogCommand.MESSAGE_USAGE
+ "\n" + DeleteLogCommand.MESSAGE_USAGE
+ "\n" + UpdateLogCommand.MESSAGE_USAGE
+ "\n" + ViewLogCommand.MESSAGE_USAGE
+ "\n" + DeleteLogCommand.MESSAGE_USAGE
+ "\n" + ViewGoalCommand.MESSAGE_USAGE
+ "\n" + AchieveGoalCommand.MESSAGE_USAGE
+ "\n" + AchievementCommand.MESSAGE_USAGE
+ "\n" + AddCommand.MESSAGE_USAGE
+ "\n" + DeleteCommand.MESSAGE_USAGE
+ "\n" + ListCommand.MESSAGE_USAGE
+ "\n" + ExitCommand.MESSAGE_USAGE);
}
}
2 changes: 1 addition & 1 deletion src/main/java/seedu/duke/commands/meal/AddCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
public class AddCommand extends MealCommand {
public static final String COMMAND_WORD = "meal_add";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Add a meal and record the amount of calories.\n"
+ "Example: " + COMMAND_WORD + " potato 15";
+ "\tExample: " + COMMAND_WORD + " potato 15";
private static final int[] validArgumentAmounts = new int[] { 3, 4 };
private final String name;
private final int calories;
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/seedu/duke/commands/meal/DeleteCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@
public class DeleteCommand extends MealCommand {
public static final String COMMAND_WORD = "meal_delete";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Delete a meal from the existing list.\n"
+ "Example: " + COMMAND_WORD + " 2";
+ "\tExample: " + COMMAND_WORD + " 2";
private static final int[] validArgumentAmounts = new int[] { 1 };
private final int index;

public DeleteCommand(List<String> arguments) throws Exception {
checkArgument(arguments, validArgumentAmounts);
index = Integer.parseInt(arguments.get(0)) - 1;
if (index <= 0) {
if (index <= -1) {
throw new Exception("Invalid index!");
}
}
Expand All @@ -26,7 +26,7 @@ public CommandResult execute() throws Exception {
return new CommandResult("Exceeded index!");
}
CommandResult result = new CommandResult(
"Successfully delete meal at index " + index + "!\n" + meals.get(index));
"Successfully delete meal at index " + (index + 1) + "!\n" + meals.get(index));
meals.remove(index);
return result;
}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/seedu/duke/commands/meal/ListCommand.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
public class ListCommand extends MealCommand {
public static final String COMMAND_WORD = "meal_list";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": List all the meals that have been recorded.\n"
+ "Example: " + COMMAND_WORD;
+ "\tExample: " + COMMAND_WORD;
private static final int[] validArgumentAmounts = new int[] { 0, 1 };
private final Category category;

Expand Down
6 changes: 3 additions & 3 deletions src/main/java/seedu/duke/parser/Parser.java
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,13 @@ public Command parseCommand(String userInput) throws Exception {
return new UpdateLogCommand(Arrays.asList(arguments.trim().split(" ")));

case AddCommand.COMMAND_WORD:
return new UpdateLogCommand(Arrays.asList(arguments.trim().split(" ")));
return new AddCommand(Arrays.asList(arguments.trim().split(" ")));

case DeleteCommand.COMMAND_WORD:
return new UpdateLogCommand(Arrays.asList(arguments.trim().split(" ")));
return new DeleteCommand(Arrays.asList(arguments.trim().split(" ")));

case ListCommand.COMMAND_WORD:
return new UpdateLogCommand(Arrays.asList(arguments.trim().split(" ")));
return new ListCommand(Arrays.asList(arguments.trim().split(" ")));

case GoalCommand.COMMAND_WORD:
return new GoalCommand(userInput);
Expand Down
181 changes: 181 additions & 0 deletions src/main/java/seedu/duke/storagefile/DataManager.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
package seedu.duke.storagefile;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;

import seedu.duke.Duke;
import seedu.duke.data.Date;
import seedu.duke.data.DateTime;
import seedu.duke.meal.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;

/**
* A util used for managing the data of the program, using the io stream to
* save and read the data at a local address.
*/
public class DataManager {
private static String absolutePath;
private static String home = System.getProperty("user.home");

/**
* Set the relative path to make clear which exact address the data file is
* going to save and read.Using relative path may make the program easier to
* modify when you need to change the absolute saving path.
*
* @param relativePath The address containing the name of the data file under
* the data folder, ignoring the address of the data folder.
* @throws IOException
*/
public static void setRelativePath(String relativePath) throws IOException {
String dataFolderPath = home + "\\AppData\\LocalLow\\FITNUS\\";
// Logger.customPrint(dataFolderPath);
Files.createDirectories(Paths.get(dataFolderPath));

absolutePath = dataFolderPath + relativePath;
// Logger.customPrint(absolutePath);
}

/**
* Read the data from the path that has been previously set.
*
* @throws IOException
*/
public static String readData() throws IOException {
File file = new File(absolutePath);

// No existing file
if (file.createNewFile()) {
return "";
}
BufferedReader reader = new BufferedReader(new FileReader(file));

String result = "", line;
while ((line = reader.readLine()) != null) {
result += line + "\n";
}
reader.close();
return result.trim();
}

/**
* Save the data to a file at the path that has been previously set.
*
* @param content The serialized data json that is going to be saved.
* @throws IOException
*/
public static void saveData(String content) throws Exception {
File file = new File(absolutePath);
file.createNewFile();

FileWriter writer = new FileWriter(file);
writer.write(content);
writer.close();
Duke.ui.showToUser("Your data has been saved at the path:\n " + absolutePath);
}

/**
* Convert a json String to a CustomType that is set by the user.
*
* @param content A valid json String indicates a CustomType instance.
*/
public static <CustomType> CustomType convertFromJson(String json) {
Type type = new TypeToken<CustomType>() {
}.getType();

Gson gson = new Gson();

return gson.fromJson(json, type);
}

/**
* Convert a json String to an ArrayList<Meal>.
*
* @param content A valid json String indicates an ArrayList<Meal>.
*/
public static ArrayList<Meal> convertFromJsonToMealList(String json) {
Type type = new TypeToken<ArrayList<Meal>>() {
}.getType();

Gson gson = new GsonBuilder()
// .registerTypeAdapter(Meal.class, new MealAdapter())
// .registerTypeAdapter(DateTime.class, new DateTimeAdapter())
.registerTypeAdapter(Date.class, new DateAdapter())
.create();

return gson.fromJson(json, type);
}

/**
* Serialize any object to json.
*
* @param object Any variable that you want to serialize.
*/
public static String convertToJson(Object object) {
Gson gson = new Gson();
return gson.toJson(object);
}

/**
* Used for deserializing Meal with a custom rule.
*/
private static class MealAdapter implements JsonDeserializer<Meal> {
@Override
public Meal deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
JsonObject jsonObject = json.getAsJsonObject();
return context.deserialize(jsonObject, Meal.class);
}
}

/**
* Used for deserializing DateTime with a custom rule.
*/
private static class DateTimeAdapter implements JsonDeserializer<DateTime> {
@Override
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
JsonObject jsonObject = json.getAsJsonObject();

String rawData = jsonObject.get("rawData").getAsString();
try {
return new DateTime(rawData);
} catch (Exception exception) {
Duke.ui.showToUser(exception.toString());
}
return null;
}
}

/**
* Used for deserializing Date with a custom rule.
*/
private static class DateAdapter implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
JsonObject jsonObject = json.getAsJsonObject();

String rawData = jsonObject.get("standardString").getAsString();
try {
return new Date(rawData, false);
} catch (Exception exception) {
Duke.ui.showToUser(exception.toString());
}
return null;
}
}
}

0 comments on commit 85c86ab

Please sign in to comment.