diff --git a/build.gradle b/build.gradle new file mode 100644 index 00000000..816e68f8 --- /dev/null +++ b/build.gradle @@ -0,0 +1,57 @@ +plugins { + id 'java' + id 'application' + id 'checkstyle' + id 'com.github.johnrengelman.shadow' version '5.1.0' +} + +repositories { + mavenCentral() +} + +dependencies { + testImplementation 'org.junit.jupiter:junit-jupiter:5.5.0' + String javaFxVersion = '11' + implementation group: 'org.openjfx', name: 'javafx-base', version: javaFxVersion, classifier: 'win' + implementation group: 'org.openjfx', name: 'javafx-base', version: javaFxVersion, classifier: 'mac' + implementation group: 'org.openjfx', name: 'javafx-base', version: javaFxVersion, classifier: 'linux' + implementation group: 'org.openjfx', name: 'javafx-controls', version: javaFxVersion, classifier: 'win' + implementation group: 'org.openjfx', name: 'javafx-controls', version: javaFxVersion, classifier: 'mac' + implementation group: 'org.openjfx', name: 'javafx-controls', version: javaFxVersion, classifier: 'linux' + implementation group: 'org.openjfx', name: 'javafx-fxml', version: javaFxVersion, classifier: 'win' + implementation group: 'org.openjfx', name: 'javafx-fxml', version: javaFxVersion, classifier: 'mac' + implementation group: 'org.openjfx', name: 'javafx-fxml', version: javaFxVersion, classifier: 'linux' + implementation group: 'org.openjfx', name: 'javafx-graphics', version: javaFxVersion, classifier: 'win' + implementation group: 'org.openjfx', name: 'javafx-graphics', version: javaFxVersion, classifier: 'mac' + implementation group: 'org.openjfx', name: 'javafx-graphics', version: javaFxVersion, classifier: 'linux' + implementation group: 'org.openjfx', name: 'javafx-media', version: javaFxVersion, classifier: 'win' + implementation group: 'org.openjfx', name: 'javafx-media', version: javaFxVersion, classifier: 'mac' + implementation group: 'org.openjfx', name: 'javafx-media', version: javaFxVersion, classifier: 'linux' + implementation group: 'org.openjfx', name: 'javafx-web', version: javaFxVersion, classifier: 'win' + implementation group: 'org.openjfx', name: 'javafx-web', version: javaFxVersion, classifier: 'mac' + implementation group: 'org.openjfx', name: 'javafx-web', version: javaFxVersion, classifier: 'linux' +} + +test { + useJUnitPlatform() +} + +application { + mainClassName = "Launcher" +} + +shadowJar { + archiveBaseName = "YanRu" + archiveVersion = "v0.1" + archiveClassifier = null + archiveAppendix = null +} + +checkstyle { + toolVersion = '8.29' +} + +run { + enableAssertions = true + standardInput = System.in +} \ No newline at end of file diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 00000000..748b3053 --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/data/tasks.txt b/data/tasks.txt new file mode 100644 index 00000000..8b313518 --- /dev/null +++ b/data/tasks.txt @@ -0,0 +1,6 @@ +[T][-] game +[D][-] project submission (by: 11/02/2021 2359) +[E][-] department retreat (at: 11/12/2021 1800-1900) +[T][+] sleep +[D][-] wash dishes (by: 20/02/2022 1900) +[E][+] dnd (at: 24/11/2017 1900-2000) \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..f3d88b1c Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..b7c8c5db --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 00000000..2fe81a7d --- /dev/null +++ b/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 00000000..62bd9b9c --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,103 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/DialogBox.java b/src/main/java/DialogBox.java new file mode 100644 index 00000000..49a2515d --- /dev/null +++ b/src/main/java/DialogBox.java @@ -0,0 +1,80 @@ +import java.io.IOException; +import java.util.Collections; + +import javafx.collections.FXCollections; +import javafx.collections.ObservableList; +import javafx.fxml.FXML; +import javafx.fxml.FXMLLoader; +import javafx.geometry.Pos; +import javafx.scene.Node; +import javafx.scene.control.Label; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.layout.HBox; +import java.io.InputStream; +import javafx.scene.text.Font; + +/** + * An example of a custom control using FXML. + * This control represents a dialog box consisting of an ImageView to represent the speaker's face and a label + * containing text from the speaker. + */ +public class DialogBox extends HBox { + @FXML + private Label dialog; + @FXML + private ImageView displayPicture; + + private DialogBox(String text, Image img) { + try { + FXMLLoader fxmlLoader = new FXMLLoader(MainWindow.class.getResource("/view/DialogBox.fxml")); + fxmlLoader.setController(this); + fxmlLoader.setRoot(this); + fxmlLoader.load(); + } catch (IOException e) { + e.printStackTrace(); + } + + dialog.setText(text); + displayPicture.setImage(img); + this.setMinHeight(this.dialog.getMinHeight()); + } + + /** + * Flips the dialog box such that the ImageView is on the left and text on the right. + */ + private void flip() { + ObservableList tmp = FXCollections.observableArrayList(this.getChildren()); + Collections.reverse(tmp); + getChildren().setAll(tmp); + setAlignment(Pos.TOP_LEFT); + } + + /** + * Retrieves font. + */ + public void getFont(String fontName, int size) { + InputStream is = Main.class.getResourceAsStream(fontName); + Font font = Font.loadFont(getClass().getResourceAsStream(fontName), 20); + this.dialog.setFont(font); + } + + /** + * Gets the dialog box. + */ + public static DialogBox getUserDialog(String text, Image img) { + var db = new DialogBox(text, img); + db.getFont("/fonts/AidaSerifaCondensed.ttf", 20); + return db; + } + + /** + * Gets the dialog box. + */ + public static DialogBox getDukeDialog(String text, Image img) { + var db = new DialogBox(text, img); + db.flip(); + db.getFont("/fonts/UniversCondensed.ttf", 20); + return db; + } +} \ No newline at end of file diff --git a/src/main/java/Duke.java b/src/main/java/Duke.java index 5d313334..ae50e62a 100644 --- a/src/main/java/Duke.java +++ b/src/main/java/Duke.java @@ -1,10 +1,74 @@ +import command.Command; +import exception.DukeException; +import filewriter.Storage; +import parser.Parser; +import task.TaskList; +import ui.Ui; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; + public class Duke { - public static void main(String[] args) { - String logo = " ____ _ \n" - + "| _ \\ _ _| | _____ \n" - + "| | | | | | | |/ / _ \\\n" - + "| |_| | |_| | < __/\n" - + "|____/ \\__,_|_|\\_\\___|\n"; - System.out.println("Hello from\n" + logo); + + private Storage storage; + private TaskList tasks; + private Ui ui; + + /** + * Constructor for Duke with no params. + * Required to for javaFx application to function. + */ + public Duke() { + String filePath = "data/tasks.txt"; + ui = new Ui(); + try { + storage = new Storage(filePath); + tasks = new TaskList(storage.load()); + } catch (DukeException e) { + ui.showLoadingError(); + tasks = new TaskList(); + } + } + + /** + * Shows the UI and stores/loads the file. + */ + public Duke(String filePath) { + ui = new Ui(); + try { + storage = new Storage(filePath); + tasks = new TaskList(storage.load()); + } catch (DukeException e) { + ui.showLoadingError(); + tasks = new TaskList(); + } + } + + /** + * You should have your own function to generate a response to user input. + * Replace this stub with your completed method. + */ + String getResponse(String input) { + try { + Command c = Parser.parse(input); + ByteArrayOutputStream outContent = new ByteArrayOutputStream(); + System.setOut(new PrintStream(outContent)); + if (c.isExit()) { + c.execute(tasks, ui, storage); + ui.showGoodbye(); + } else { + c.execute(tasks, ui, storage); + + } + return outContent.toString(); + } catch (DukeException e) { + return e.getMessage(); + } catch (NullPointerException e) { + StringWriter errors = new StringWriter(); + e.printStackTrace(new PrintWriter(errors)); + return errors.toString(); + } } } + diff --git a/src/main/java/Launcher.java b/src/main/java/Launcher.java new file mode 100644 index 00000000..8b31d13e --- /dev/null +++ b/src/main/java/Launcher.java @@ -0,0 +1,11 @@ +import javafx.application.Application; + +/** + * A launcher class to workaround classpath issues. + */ +public class Launcher { + + public static void main(String[] args) { + Application.launch(Main.class, args); + } +} \ No newline at end of file diff --git a/src/main/java/Main.java b/src/main/java/Main.java new file mode 100644 index 00000000..89d0cdbd --- /dev/null +++ b/src/main/java/Main.java @@ -0,0 +1,29 @@ +import java.io.IOException; +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Scene; +import javafx.scene.layout.AnchorPane; +import javafx.stage.Stage; + +/** + * A GUI for Duke using FXML. + */ +public class Main extends Application { + + private Duke duke = new Duke(); + + @Override + public void start(Stage stage) { + try { + FXMLLoader fxmlLoader = new FXMLLoader(Main.class.getResource("/view/MainWindow.fxml")); + AnchorPane ap = fxmlLoader.load(); + Scene scene = new Scene(ap); + stage.setScene(scene); + stage.setTitle("Duke - Your friendly Task Manager"); + fxmlLoader.getController().setDuke(duke); + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/src/main/java/MainWindow.java b/src/main/java/MainWindow.java new file mode 100644 index 00000000..1be5a27a --- /dev/null +++ b/src/main/java/MainWindow.java @@ -0,0 +1,64 @@ +import javafx.fxml.FXML; +import javafx.scene.control.Button; +import javafx.scene.control.ScrollPane; +import javafx.scene.control.TextField; +import javafx.scene.image.Image; +import javafx.scene.layout.AnchorPane; +import javafx.scene.layout.VBox; +import javafx.animation.PauseTransition; +import javafx.application.Platform; +import javafx.util.Duration; + +/** + * Controller for MainWindow. Provides the layout for the other controls. + */ +public class MainWindow extends AnchorPane { + @FXML + private ScrollPane scrollPane; + @FXML + private VBox dialogContainer; + @FXML + private TextField userInput; + @FXML + private Button sendButton; + + private Duke duke; + + private Image userImage = new Image(this.getClass().getResourceAsStream("/images/UserYAN.png")); + private Image dukeImage = new Image(this.getClass().getResourceAsStream("/images/AdminDUKE.png")); + + /** + * Controller for MainWindow. Provides the layout for the other controls. + */ + @FXML + public void initialize() { + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + VBox.setVgrow(scrollPane, javafx.scene.layout.Priority.ALWAYS); + dialogContainer.getChildren().addAll(DialogBox.getDukeDialog("Hello! I'm Duke. " + + "How may I help you?", dukeImage)); + } + + public void setDuke(Duke d) { + duke = d; + } + + /** + * Creates two dialog boxes, one echoing user input and the other containing Duke's reply and then appends them to + * the dialog container. Clears the user input after processing. + */ + @FXML + private void handleUserInput() { + String input = userInput.getText(); + String response = duke.getResponse(input); + dialogContainer.getChildren().addAll( + DialogBox.getUserDialog(input, userImage), + DialogBox.getDukeDialog(response, dukeImage) + ); + userInput.clear(); + if (input.equals("bye")) { + PauseTransition pause = new PauseTransition(Duration.seconds(1)); + pause.setOnFinished(event -> Platform.exit()); + pause.play(); + } + } +} \ No newline at end of file diff --git a/src/main/java/command/AddCommand.java b/src/main/java/command/AddCommand.java new file mode 100644 index 00000000..010342cd --- /dev/null +++ b/src/main/java/command/AddCommand.java @@ -0,0 +1,60 @@ +package command; + +import exception.DukeException; +import filewriter.Storage; +import task.Deadline; +import task.Event; +import task.Task; +import task.TaskList; +import task.Todo; +import ui.Ui; + +/** + * Adds a new Task to Task list. + */ +public class AddCommand extends Command { + String specifics; + + /** + * Constructor for AddCommand. + * @param taskType type of command/task (e.g. deadline, event, find etc). + * @param specifics includes the command/task name as well as the date and time specially for DEADLINE and EVENT. + */ + public AddCommand(FullCommand taskType, String specifics) { + super.type = taskType; + this.specifics = specifics; + } + + /** + * Checks if command is an ExitCommand. + * @return false as command will be AddCommand. + */ + public boolean isExit() { + assert (!super.type.getActivityName().equals("bye")); + return false; + } + + /** + * Adds task corresponding to command type and specifics to TaskList. + * @param tasks TaskList to add the task to. + * @param ui Instance of user interface to print feedback to user. + * @param storage Updates data record of TaskList stored in storage.filepath. + * @throws DukeException Creates new Deadline and Event, throws exception if not written in correct format. + */ + public void execute(TaskList tasks, Ui ui, Storage storage) throws DukeException { + Task newTask; + switch (type) { + case TODO: + newTask = new Todo(specifics); + break; + case DEADLINE: + newTask = new Deadline(specifics); + break; + default: + newTask = new Event(specifics); + break; + } + tasks.addTask(newTask); + ui.readTask(newTask, tasks.taskNum); + } +} \ No newline at end of file diff --git a/src/main/java/command/Command.java b/src/main/java/command/Command.java new file mode 100644 index 00000000..7e108b54 --- /dev/null +++ b/src/main/java/command/Command.java @@ -0,0 +1,31 @@ +package command; + +import exception.DukeException; +import filewriter.Storage; +import task.TaskList; +import ui.Ui; + +/** + * Abstract class for all other command classes to extend to (e.g. DeleteCommand, etc.), except FulLCommand enum. + */ +public abstract class Command { + FullCommand type; + + /** + * Checks to see if type equals FullCommand.BYE. + * @return boolean value to check if this is an Exit command. + */ + public boolean isExit() { + return type.getActivityName().equals("bye"); + } + + /** + * Carries out the command. + * @param tasks Current TaskList object used in this instance of Duke. + * @param ui Instance of user interface to print feedback to user. + * @param storage Updates data record of TaskList in storage.filepath if needed. + * @throws DukeException Various subclass of Command may throw DukeException when + * executed with invalid specification. + */ + public abstract void execute(TaskList tasks, Ui ui, Storage storage) throws DukeException; +} \ No newline at end of file diff --git a/src/main/java/command/DeleteCommand.java b/src/main/java/command/DeleteCommand.java new file mode 100644 index 00000000..7f5b361e --- /dev/null +++ b/src/main/java/command/DeleteCommand.java @@ -0,0 +1,51 @@ +package command; + +import exception.DukeException; +import filewriter.Storage; +import task.Task; +import task.TaskList; +import ui.Ui; + +/** + * Removes Task from Task List. + */ +public class DeleteCommand extends Command { + int index; + + /** + * Constructor for DeleteCommand. + * @param index of the task to delete in the Task List. + */ + public DeleteCommand(int index) { + this.index = index; + super.type = FullCommand.DELETE; + } + + /** + * Checks if command is an ExitCommand. + * @return false as command is a DeleteCommand. + */ + public boolean isExit() { + assert (!super.type.getActivityName().equals("bye")); + return false; + } + + /** + * Removes the current (index)th task from the task list. + * @param tasks Current TaskList object used in this instance of Duke. Removes specified task from tasks.schedule. + * @param ui Instance of user interface to print feedback to user. + * @param storage Updates data record of TaskList in storage.filepath. + * @throws DukeException Throws when index equals to 0, or when index is larger than number of Task(s) in TaskList. + */ + public void execute(TaskList tasks, Ui ui, Storage storage) throws DukeException { + try { + Task removeTask = tasks.remove(index); + ui.readDelete(removeTask, tasks.taskNum); + } catch (NullPointerException | IndexOutOfBoundsException e) { + throw new DukeException("The task number is not in the list. Please enter 'list' to check the task number " + + "that you wish to delete."); + } catch (NumberFormatException e) { + throw new DukeException("Please enter the task number that you would like to delete."); + } + } +} \ No newline at end of file diff --git a/src/main/java/command/EditCommand.java b/src/main/java/command/EditCommand.java new file mode 100644 index 00000000..6af16cac --- /dev/null +++ b/src/main/java/command/EditCommand.java @@ -0,0 +1,52 @@ +package command; + +import exception.DukeException; +import filewriter.Storage; +import task.Task; +import task.TaskList; +import ui.Ui; + +public class EditCommand extends Command { + int index; + + /** + * Checks if command is an ExitCommand. + * @return false as command is an EditCommand. + */ + public boolean isExit() { + assert (!super.type.getActivityName().equals("bye")); + return false; + } + + /** + * Constructor for EditCommand. + * @param index of Task in TaskList to mark as done. + */ + public EditCommand(int index) { + this.index = index; + super.type = FullCommand.DONE; + } + + /** + * Marks the (index)th task in TaskList as done. + * @param tasks Current TaskList object used in this instance of Duke. + * @param ui Instance of user interface to print feedback to user. + * @param storage Updates data record of TaskList in storage.filepath if needed. + * @throws DukeException Throws when index equals to, or when index is larger than number of Task(s) in TaskList, + * or when index of Task to markAsComplete is not properly presented. + */ + public void execute(TaskList tasks, Ui ui, Storage storage) throws DukeException { + try { + if (index == -1) { + throw new IndexOutOfBoundsException(); + } + Task completedTask = tasks.complete(index); + ui.readDone(completedTask); + } catch (NullPointerException | IndexOutOfBoundsException e) { + throw new DukeException("The task number is not in the list. Please enter 'list' to check the task number " + + "that you have completed."); + } catch (NumberFormatException e) { + throw new DukeException("Please enter the task number that you have completed."); + } + } +} \ No newline at end of file diff --git a/src/main/java/command/ExitCommand.java b/src/main/java/command/ExitCommand.java new file mode 100644 index 00000000..885764dd --- /dev/null +++ b/src/main/java/command/ExitCommand.java @@ -0,0 +1,35 @@ +package command; + +import exception.DukeException; +import filewriter.Storage; +import task.TaskList; +import ui.Ui; + +public class ExitCommand extends Command { + + /** + * Ends program. + */ + public ExitCommand() { + super.type = FullCommand.BYE; + } + + /** Uses by Duke class method run to check for exit command and terminate program if exit command is found. + * @return true as command is ExitCommand. + */ + public boolean isExit() { + assert (super.type.getActivityName().equals("bye")); + return true; + } + + /** + * Closes FileWriter used by storage. + * @param tasks current TaskList object used in this instance of Duke. Not needed here. + * @param ui Instance of user interface to print feedback to user. Not needed here. + * @param storage closes FileWriter of storage. Changes to Task List are recorded in storage.filepath. + * @throws DukeException if invalid filepath (Directory tampered with when program is running). + */ + public void execute(TaskList tasks, Ui ui, Storage storage) throws DukeException { + storage.write(tasks); + } +} \ No newline at end of file diff --git a/src/main/java/command/FindCommand.java b/src/main/java/command/FindCommand.java new file mode 100644 index 00000000..1e07093b --- /dev/null +++ b/src/main/java/command/FindCommand.java @@ -0,0 +1,57 @@ +package command; + +import exception.DukeException; +import filewriter.Storage; +import task.Task; +import task.TaskList; +import ui.Ui; +import java.util.ArrayList; + +/** + * Lists all tasks containing keyword. + */ +public class FindCommand extends Command { + String keyword; + + /** + * Constructor for FindCommand. + * @param keyword Searches for all tasks with keyword. + */ + public FindCommand(String keyword) { + super.type = FullCommand.FIND; + this.keyword = keyword; + } + + /** + * Checks if it is an ExitCommand. + * @return false. + */ + public boolean isExit() { + assert (!super.type.getActivityName().equals("bye")); + return false; + } + + /** + * Generates a TaskList shortlist containing only tasks with the keyword. + * Passes TaskList as an argument for ui.showMatches to display to user. + * @param tasks TaskList containing all Tasks. + * @param ui Instance of user interface to print feedback to user. + * @param storage Updates data record of TaskList in storage.filepath if needed. + * @throws DukeException when command cannot be found. + */ + public void execute(TaskList tasks, Ui ui, Storage storage) throws DukeException { + ArrayList shortlist = new ArrayList<>(); + try { + for (Task task : tasks.getList()) { + if (task.findWord(keyword)) { + shortlist.add(task); + } + } + ui.showMatches(new TaskList(shortlist)); + } catch (NullPointerException | IndexOutOfBoundsException e) { + throw new DukeException("No such keyword in the task list. Please try again. "); + } catch (NumberFormatException e) { + throw new DukeException("Please enter the keyword that you wish to search in the list."); + } + } +} \ No newline at end of file diff --git a/src/main/java/command/FullCommand.java b/src/main/java/command/FullCommand.java new file mode 100644 index 00000000..c569a5bf --- /dev/null +++ b/src/main/java/command/FullCommand.java @@ -0,0 +1,46 @@ +package command; + +import exception.DukeException; + +/** + * Enum detailing all the valid commands Duke understands. + * Uses by Parser to generate Command Object. + * Checks if user types invalid command. + */ +public enum FullCommand { + LIST("list"), + TODO("todo"), + EVENT("event"), + DEADLINE("deadline"), + DONE("done"), + DELETE("delete"), + BYE("bye"), + FIND("find"), + VIEW("view"), + INSTRUCTION("instruction"); + + private String activityName; + + FullCommand(String activityName) { + this.activityName = activityName; + } + + public String getActivityName() { + return activityName; + } + + /** + * Generates FullCommand based on String user input. + * @param keyword Specifies the type of FullCommand. + * @return Returns FullCommand to be parsed by parser. + * @throws DukeException Throws when user enters invalid command. + */ + public static FullCommand getByAction(String keyword) throws DukeException { + for (FullCommand activity : values()) { + if (activity.getActivityName().equals(keyword)) { + return activity; + } + } + throw new DukeException("\nCommand does not exist."); + } +} diff --git a/src/main/java/command/InstructionCommand.java b/src/main/java/command/InstructionCommand.java new file mode 100644 index 00000000..aa9fd386 --- /dev/null +++ b/src/main/java/command/InstructionCommand.java @@ -0,0 +1,39 @@ +package command; + +import exception.DukeException; +import filewriter.Storage; +import task.TaskList; +import ui.Ui; + +/** + * Displays the instructions to the user. + */ +public class InstructionCommand extends Command { + + /** + * Constructor of instructions. + */ + public InstructionCommand() { + super.type = FullCommand.INSTRUCTION; + } + + /** + * Checks if command is an ExitCommand. + * @return InstructionCommand is not ExitCommand. + */ + public boolean isExit() { + assert (!super.type.getActivityName().equals("bye")); + return false; + } + + /** + * Passes TaskList as an argument for ui.readInstruction to display to user. + * @param tasks Current TaskList object used in this instance of Duke. + * @param ui Instance of user interface to print feedback to user. + * @param storage Updates data record of TaskList in storage.filepath if needed. + * @throws DukeException if the number is not in the list or no number was indicated. + */ + public void execute(TaskList tasks, Ui ui, Storage storage) throws DukeException { + ui.readInstruction(); + } +} \ No newline at end of file diff --git a/src/main/java/command/ListCommand.java b/src/main/java/command/ListCommand.java new file mode 100644 index 00000000..18ab5a56 --- /dev/null +++ b/src/main/java/command/ListCommand.java @@ -0,0 +1,50 @@ +package command; + +import exception.DukeException; +import filewriter.Storage; +import task.TaskList; +import ui.Ui; + +/** + * Displays the full list of recorded tasks to user. + */ +public class ListCommand extends Command { + int index; + + /** + * Constructor of ListCommand. + */ + public ListCommand() { + super.type = FullCommand.LIST; + } + + /** + * Checks if command is an ExitCommand. + * @return ConstructorCommand is not ExitCommand. + */ + public boolean isExit() { + assert (!super.type.getActivityName().equals("bye")); + return false; + } + + /** + * Passes TaskList as an argument for ui.readList to display to user. + * @param tasks Current TaskList object used in this instance of Duke. + * @param ui Instance of user interface to print feedback to user. + * @param storage Updates data record of TaskList in storage.filepath if needed. + * @throws DukeException if the number is not in the list or no number was indicated. + */ + public void execute(TaskList tasks, Ui ui, Storage storage) throws DukeException { + try { + if (index == -1) { + throw new IndexOutOfBoundsException(); + } + ui.readList(tasks); + } catch (NullPointerException | IndexOutOfBoundsException e) { + throw new DukeException("You have 0 task in the list."); + } catch (NumberFormatException e) { + throw new DukeException("Please provide commands in the format: (command type) (task details). " + + "For more information, please type 'instruction'."); + } + } +} \ No newline at end of file diff --git a/src/main/java/command/ViewScheduleCommand.java b/src/main/java/command/ViewScheduleCommand.java new file mode 100644 index 00000000..b761cacb --- /dev/null +++ b/src/main/java/command/ViewScheduleCommand.java @@ -0,0 +1,67 @@ +package command; + +import exception.DukeException; +import filewriter.Storage; +import task.Task; +import task.TaskList; +import ui.Ui; +import java.util.ArrayList; + +/** + * View tasks in the form of a schedule e.g., view the schedule for a specific date + */ +public class ViewScheduleCommand extends Command { + String schedule; + + /** + * Constructor for ViewScheduleCommand. + * @param schedule Searches for all tasks with dateTime schedule. + */ + public ViewScheduleCommand(String schedule) { + super.type = FullCommand.VIEW; + this.schedule = schedule; + } + + + /** + * Checks if command is an ExitCommand. + * @return false. + */ + public boolean isExit() { + assert (!super.type.getActivityName().equals("bye")); + return false; + } + + /** + * Generates a TaskList shortlist containing only tasks with the dateTime schedule. + * Passes TaskList as an argument for ui.showSchedule to display to user. + * @param tasks TaskList containing all Tasks. + * @param ui Instance of user interface to print feedback to user. + * @param storage Updates data record of TaskList in storage.filepath if needed. + * @throws DukeException when command cannot be found. + */ + public void execute(TaskList tasks, Ui ui, Storage storage) throws DukeException { + ArrayList shortlist = new ArrayList<>(); + try { + for (Task task : tasks.getList()) { + if (schedule.equals("all")) { + if (task.toString().contains("/")) { + shortlist.add(task); + } + } else if (task.toString().contains(schedule)) { + shortlist.add(task); + } + } + if (schedule.equals("all")) { + ui.showAllSchedule(new TaskList(shortlist)); + } else { + ui.showSchedule(new TaskList(shortlist)); + } + } catch (NullPointerException | IndexOutOfBoundsException e) { + throw new DukeException("You do not have any tasks in the mentioned schedule."); + } catch (NumberFormatException e) { + throw new DukeException("Please enter the schedule " + + "(i.e. specific date) that you wish to search in the list."); + } + } +} \ No newline at end of file diff --git a/src/main/java/datetime/DateTime.java b/src/main/java/datetime/DateTime.java new file mode 100644 index 00000000..37e77370 --- /dev/null +++ b/src/main/java/datetime/DateTime.java @@ -0,0 +1,129 @@ +package datetime; + +import java.time.format.DateTimeFormatter; +import java.time.LocalTime; +import java.time.LocalDateTime; +import exception.DukeException; + +import java.time.format.DateTimeParseException; +import java.util.ArrayList; + +/** + * Wrapper of LocalDateTime. + * Stores date and time for Task. + */ +public class DateTime { + private LocalTime endDateTime; + public LocalDateTime startDateTime; + public String displayDateTime; + private static DateTimeFormatter getTime = DateTimeFormatter.ofPattern("HHmm"); + private static DateTimeFormatter getStartDateTime = DateTimeFormatter.ofPattern("d/MM/yyyy HHmm"); + + /** + * Calls during construction of Deadline object. + * Reads substring from user input and gets date and time of task. + * @param dateTime Must be in the form (d/MM/yyyy HHmm) + * @return DateTime object as dateTime parameter of Deadline object. + * @throws DukeException Throws if dateTime is not presented in the correct form. + */ + public static DateTime setDeadline(String dateTime) throws DukeException { + try { + DateTime deadlineDateTime = new DateTime(); + deadlineDateTime.startDateTime = LocalDateTime.parse(dateTime, getStartDateTime); + deadlineDateTime.displayDateTime = deadlineDateTime.startDateTime.format(getStartDateTime); + return deadlineDateTime; + } catch (DateTimeParseException e) { + throw new DukeException("Incorrect deadline datetime format." + + "\nPlease key in deadline (details) /by (date)d/mm/yyyy (time)HHmm."); + } + } + + /** + * Calls during construction of Deadline object. + * Reads substring from text file and gets date and time of the task. + * @param dateTime Must be in the form (d/MM/yyyy HHmm). + * @return DateTime object as dateTime parameter of Deadline object. + */ + public static DateTime readDeadLine(String dateTime) { + DateTime deadlineDateTime = new DateTime(); + deadlineDateTime.startDateTime = LocalDateTime.parse(dateTime, getStartDateTime); + deadlineDateTime.displayDateTime = deadlineDateTime.startDateTime.format(getStartDateTime); + return deadlineDateTime; + } + + /** + * Calls during construction of Event object. + * Reads substring from user input and gets date, start time and end time of task. + * @param dateTime Must be in the form (d/MM/yyyy HHmm-HHmm). + * @return DateTime object as dateTime parameter of Event object. + * @throws DukeException Throws if missing end time or if dateTime is not presented in the correct form. + */ + public static DateTime setEventTime(String dateTime) throws DukeException { + try { + DateTime eventDateTime = new DateTime(); + int divider = dateTime.indexOf("-"); + if (divider == -1 || (divider == dateTime.length() - 1)) { + throw new DukeException("Please key in the end time."); + } + String end = dateTime.substring(divider + 1, dateTime.length()); + eventDateTime.startDateTime = LocalDateTime.parse(dateTime.substring(0, divider), getStartDateTime); + eventDateTime.endDateTime = LocalTime.parse(end, DateTimeFormatter.ofPattern("HHmm")); + eventDateTime.displayDateTime = eventDateTime.startDateTime.format(getStartDateTime) + "-" + + eventDateTime.endDateTime.format(getTime); + return eventDateTime; + } catch (DateTimeParseException e) { + throw new DukeException("Incorrect event format." + + "\nPlease key in event (details) /at (date)d/mm/yyyy (start time)HHmm-(end time)HHmm."); + } + } + + /** + * Calls during construction of Event object. + * Reads substring from text file and gets date, start time and end time of task. + * @param dateTime Must be in the form (d/M/yyyy HHmm-HHmm) + * @return DateTime object as dateTime parameter of Event object. + * @throws DukeException Throws if missing end time. This should not happen unless text file was tampered with. + */ + public static DateTime readEventTime(String dateTime) throws DukeException { + DateTime eventDateTime = new DateTime(); + int divider = dateTime.indexOf("-"); + if (divider == -1 || (divider == dateTime.length() - 1) + || dateTime.substring(divider + 1).replace(" ", "").equals("")) { + throw new DukeException("Please key in the end time."); + } + String end = dateTime.substring(divider + 1, dateTime.length()); + eventDateTime.startDateTime = LocalDateTime.parse(dateTime.substring(0,divider), getStartDateTime); + eventDateTime.endDateTime = LocalTime.parse(end, DateTimeFormatter.ofPattern("HHmm")); + eventDateTime.displayDateTime = (eventDateTime.startDateTime.format(getStartDateTime) + "-" + + eventDateTime.endDateTime.format(getTime)); + return eventDateTime; + } + + /** + * Adds suffix to date of month. + * @param dd day of month as a 2 digits number. + * @return 1 or 2 digits number with appropriate suffix. + */private static String getDayOfMonth(String dd) { + if (dd.substring(0, 1).equals("0")) { + dd = dd.substring(1, dd.length()); + } + int day = Integer.parseInt(dd); + if (day >= 11 && day <= 31) { + return day + "th"; + } + switch (day & 10) { + case 1: + return day + "st"; + case 2: + return day + "nd"; + case 3: + return day + "rd"; + default: + return day + "th"; + } + } + + public String toString() { + return displayDateTime; + } +} diff --git a/src/main/java/exception/DukeException.java b/src/main/java/exception/DukeException.java new file mode 100644 index 00000000..f321c58d --- /dev/null +++ b/src/main/java/exception/DukeException.java @@ -0,0 +1,15 @@ +package exception; + +/** + * Wraps exception. Helps to check if exception has been accounted for. + * Catches exception and throws DukeException. + */ +public class DukeException extends Exception { + public DukeException(String message) { + super(message); + } + + public DukeException(String message, Throwable cause) { + super(message,cause); + } +} diff --git a/src/main/java/filewriter/Storage.java b/src/main/java/filewriter/Storage.java new file mode 100644 index 00000000..ffb47d96 --- /dev/null +++ b/src/main/java/filewriter/Storage.java @@ -0,0 +1,139 @@ +package filewriter; + +import datetime.DateTime; +import exception.DukeException; +import task.Deadline; +import task.Event; +import task.Task; +import task.TaskList; +import task.Todo; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * Class of storage. + * Stores and reads from text file. + */ +public class Storage { + String filePath; + FileWriter fw; + ArrayList taskList; + boolean isAppend = true; + + /** + * Constructor of Storage object. + * @param filePath filepath to text file to be read from and edited. + * @throws DukeException When CreateWriter throws DukeException. + */ + public Storage(String filePath) throws DukeException { + this.filePath = filePath; + } + + /** + * Creates FileWriter member fw. + * @throws DukeException when invalid filepath. + */ + public void write(TaskList schedule) throws DukeException { + try { + File text = new File(filePath); + text.getParentFile().mkdirs(); + fw = new FileWriter(text, false); + fw.write(schedule.toText()); + fw.close(); + } catch (IOException e) { + throw new DukeException("Error creating file writer"); + } + } + + /** + * Interprets each line in txt file and add corresponding Task to TaskList. + * @param line every line in the txt file represents a task. + * @return Task object with type, task name, date and timing as described in String. + * @throws DukeException Throws when Task is not stored in the correct format in txt file. + */ + private Task read(String line) throws DukeException { + Task output; + switch (line.charAt(line.indexOf("[") + 1)) { + case 'T': + output = new Todo(line.substring(7, line.length())); + updateStatus(output, line); + return output; + case 'D': + try { + int divider = line.indexOf("(by:"); + String input = line.substring(7, divider); + input += "/by " + DateTime.readDeadLine(line.substring(divider + 5, line.length() - 1)).toString(); + output = new Deadline(input); + updateStatus(output, line); + return output; + } catch (Exception e) { + System.out.println(e.getMessage()); + throw new DukeException("\n Deadline task not stored properly."); + } + default: + try { + int divider = line.indexOf("(at:"); + String input = line.substring(7, divider); + input += "/at " + DateTime.readEventTime(line.substring(divider + 5, line.length() - 1)).toString(); + output = new Event(input); + updateStatus(output, line); + return output; + } catch (Exception e) { + throw new DukeException("\n Event task not stored properly."); + } + } + } + + private void updateStatus(Task task, String line) { + if (line.substring(4,5).equals("+")) { + task.markAsDone(); + } + } + + /** + * Reads txt file and updates TaskList accordingly. + * @return Storage object with updated Task taskList used in construction of TaskList object. + * @throws DukeException when read throws DukeException. + */ + public Storage load() throws DukeException { + try { + taskList = new ArrayList<>(); + File text = new File(filePath); + text.createNewFile(); + text.getParentFile().mkdirs(); + BufferedReader reader = new BufferedReader(new FileReader(text)); + Stream stream + = reader.lines(); + taskList = new ArrayList(stream.filter(line -> !line.equals("")) + .map(line -> { + try { + return read(line); + } catch (DukeException e) { + throw new RuntimeException(); + } + }).collect(Collectors.toList())); + return this; + } catch (FileNotFoundException e) { + throw new DukeException("File not found! \n "); + } catch (IOException e) { + return null; + } catch (Exception e) { + throw new DukeException("Unexpected Error: " + e.getMessage()); + } + } + + /** + * Calls during construction method of TaskList. + * @return ArrayList of Task + */ + public ArrayList getSchedule() { + return taskList; + } +} \ No newline at end of file diff --git a/src/main/java/parser/Parser.java b/src/main/java/parser/Parser.java new file mode 100644 index 00000000..2a500c4d --- /dev/null +++ b/src/main/java/parser/Parser.java @@ -0,0 +1,57 @@ +package parser; + +import command.AddCommand; +import command.Command; +import command.DeleteCommand; +import command.EditCommand; +import command.ExitCommand; +import command.FindCommand; +import command.FullCommand; +import command.InstructionCommand; +import command.ListCommand; +import command.ViewScheduleCommand; +import exception.DukeException; + +/** + * Parses String user input/ text file to get corresponding Command object to execute. + */ +public class Parser { + /** + * Processes user input/ line from txt file and gets appropriate command. + * @param instruction String from user input/ text file + * @return Corresponding Task to be executed in run method of Duke class. + * @throws DukeException When there are no matching command. i.e. user input or line from txt file is invalid. + */ + public static Command parse(String instruction) throws DukeException { + String[] arr = instruction.split(" ", 2); + FullCommand command = FullCommand.getByAction(arr[0]); + try { + switch (command) { + case LIST: + return new ListCommand(); + case BYE: + return new ExitCommand(); + case DONE: + return new EditCommand(Integer.parseInt(arr[1]) - 1); + case DELETE: + return new DeleteCommand(Integer.parseInt(arr[1]) - 1); + case FIND: + return new FindCommand(arr[1]); + case VIEW: + return new ViewScheduleCommand(arr[1]); + case INSTRUCTION: + return new InstructionCommand(); + default: + if (arr[1].equals("")) { + throw new DukeException(""); + } + return new AddCommand(command, arr[1]); + } + } catch (IndexOutOfBoundsException e) { + throw new DukeException("Please provide commands in the format: (command type) (task details). " + + "For more information, please type 'instruction'."); + } catch (NumberFormatException e) { + throw new DukeException("For command 'done' and 'delete', it must be followed by an integer index."); + } + } +} diff --git a/src/main/java/task/Deadline.java b/src/main/java/task/Deadline.java new file mode 100644 index 00000000..1dd430e9 --- /dev/null +++ b/src/main/java/task/Deadline.java @@ -0,0 +1,38 @@ +package task; + +import datetime.DateTime; +import exception.DukeException; + +/** + * Deadline task object. Has a task name, date and time. + */ +public class Deadline extends Task { + DateTime dateTime; + + /** + * Constructor for Deadline object. Calls when generating TaskList based on user input. + * @param description Includes task name, date and time. + * @throws DukeException Throws when description format is incorrect. or when setDeadline throws DukeException. + */ + public Deadline(String description) throws DukeException { + super(description); + int divider = description.indexOf("/by"); + if (divider == -1 || (divider == description.length() - 3) + || description.substring(divider + 4).replace(" ", "").equals("")) { + throw new DukeException("Incorrect deadline format.\nPlease key in deadline (task) " + + "/by (date)d/mm/yyyy (time)HHmm."); + } + dateTime = DateTime.setDeadline(description.substring(divider + 4, description.length())); + super.taskDesc = super.taskDesc.substring(0,divider); + } + + /** + * toString method of DeadLine. + * @return String denoting task name, status date and time of Deadline task. + */ + @Override + public String toString() { + String output = "[D][" + super.getStatus() + "]" + " " + super.taskDesc + "(by: " + dateTime.toString() + ")"; + return output; + } +} diff --git a/src/main/java/task/Event.java b/src/main/java/task/Event.java new file mode 100644 index 00000000..2361d4ac --- /dev/null +++ b/src/main/java/task/Event.java @@ -0,0 +1,36 @@ +package task; + +import datetime.DateTime; +import exception.DukeException; + +public class Event extends Task { + DateTime dateTime; + + /** + * Constructor for Event object. Calls when generating TaskList based on user input. + * @param description Contains task name, date, starting time and ending time. + * @throws DukeException Throws when description format is incorrect. or when setEventTime throws DukeException. + */ + public Event(String description) throws DukeException { + super(description); + int divider = description.indexOf("/at"); + if (divider == -1 || (divider == description.length() - 3) + || description.substring(divider + 4).replace(" ", "").equals("")) { + throw new DukeException("Incorrect event format.\n" + + "Please key in event (details) /at (date)d/mm/yyyy (start time)HHmm-(end time)HHmm."); + } + dateTime = DateTime.setEventTime(description.substring(divider + 4, description.length())); + super.taskDesc = super.taskDesc.substring(0,divider); + } + + /** + * toString method of Event. + * @return String denoting task name, status, date, and starting and ending time of task. + */ + @Override + public String toString() { + String output = "[E][" + super.getStatus() + "]" + " " + super.taskDesc + + "(at: " + dateTime.toString() + ")"; + return output; + } +} diff --git a/src/main/java/task/Task.java b/src/main/java/task/Task.java new file mode 100644 index 00000000..a85ac283 --- /dev/null +++ b/src/main/java/task/Task.java @@ -0,0 +1,51 @@ +package task; + +/** + * Abstract class which all other Task classes extend (Event, deadline etc.). + */ +public abstract class Task { + protected String taskDesc; + protected boolean isDone; + protected boolean isDeleted; + + /** + * Constructor method of Task. + * @param taskDesc contains information of Task, includes task name and may include date and time. + */ + public Task(String taskDesc) { + this.taskDesc = taskDesc; + this.isDone = false; + this.isDeleted = false; + } + + /** + * Calls when execute method of findCommand is called. + * Checks to see if description of task contains keyword. + * @param keyword word/phrase to find in description. + * @return boolean value indicating if word/phrase can be found in description. + */ + public boolean findWord(String keyword) { + if (taskDesc.indexOf(keyword) == -1) { + return false; + } else { + return true; + } + } + + /** + * Calls in toString method. Indicates status of completion of task. + * @return //+ if done, else - + */ + public String getStatus() { + return (isDone ? "+" : "-"); + } + + /** + * sets isDone value to true. + */ + public void markAsDone() { + this.isDone = true; + } + + public abstract String toString(); +} diff --git a/src/main/java/task/TaskList.java b/src/main/java/task/TaskList.java new file mode 100644 index 00000000..3eb92bfb --- /dev/null +++ b/src/main/java/task/TaskList.java @@ -0,0 +1,169 @@ +package task; + +import exception.DukeException; +import filewriter.Storage; +import java.util.ArrayList; + +/** + * Object containing data structure to store Tasks. + */ +public class TaskList { + ArrayList taskList = new ArrayList<>(); + public int taskNum; + public boolean isFirst; + + /** + * Constructor for Task List. + * Calls when generating Task List from txt file. + * @param storage Contains ArrayList of Task specified from txt file. + */ + public TaskList(Storage storage) { + try { + this.taskList = storage.getSchedule(); + taskNum = taskList.size(); + if (taskNum == 0) { + isFirst = true; + } else { + isFirst = false; + } + } catch (Exception e) { + System.out.println(e.getMessage()); + } + } + + /** + * Constructor for Task List. + */ + public TaskList() { + this.taskList = new ArrayList(); + taskNum = taskList.size(); + if (taskNum == 0) { + isFirst = true; + } else { + isFirst = false; + } + } + + + /** + * Constructor for Task List. + * @param schedule ArrayList of tasks. + */ + public TaskList(ArrayList schedule) { + this.taskList = schedule; + taskNum = taskList.size(); + if (taskNum == 0) { + isFirst = true; + } else { + isFirst = false; + } + } + + /** + * Gets Task corresponding to specified index. + * @param index Indicates which task in the task list to return. + * @return Task as specified by index. + */ + public Task getTask(int index) { + return taskList.get(index); + } + + /** + * Marks a Task in task list as done. + * @param index Specifies which task to mark as done. + * @return completed Task. + * @throws NullPointerException Throws when an application attempts + * to use null in a case where an object is required. + * @throws IndexOutOfBoundsException Throws to indicate that an index of + * some sort (such as to an array, to a string, or to a vector) is out of range. + * @throws NumberFormatException Throws to indicate that the application has attempted to convert a string to + * one of the numeric types, but that the string does not have appropriate format. + * @throws DukeException Wraps exception. Helps to check if + * exception has been accounted for. Catches exception and throws DukeException. + */ + public Task complete(int index) throws NullPointerException, IndexOutOfBoundsException, + NumberFormatException, DukeException { + Task completedTask = taskList.get(index); + completedTask.markAsDone(); + return completedTask; + } + + /** + * Adds new Task to TaskList. + * @param task to add a new task. + * @throws DukeException if unexpected error occurs. + */ + public void addTask(Task task) throws DukeException { + taskList.add(task); + taskNum++; + } + + /** + * Deletes Task from TaskList. + * @param index based on the index number. + * @return deleted Task. + * @throws NullPointerException Throws when an application attempts + * to use null in a case where an object is required. + * @throws IndexOutOfBoundsException Throws to indicate that an index of + * some sort (such as to an array, to a string, or to a vector) is out of range. + * @throws NumberFormatException Throws to indicate that the application has attempted to convert a string to + * one of the numeric types, but that the string does not have appropriate format. + * @throws DukeException Wraps exception. Helps to check if + * exception has been accounted for. Catches exception and throws DukeException. + */ + public Task remove(int index) throws NullPointerException, IndexOutOfBoundsException, + NumberFormatException, DukeException { + Task removeTask = taskList.get(index); + taskList.remove(index); + taskNum--; + return removeTask; + } + + /** + * Retrieves Task schedule from TaskList array. + * Calls when execute method of FindCommand is called. + * @return Task schedule from TaskList array. + */ + public ArrayList getList() { + return taskList; + } + + /** + * toString method of TaskList. + * @return contents of TaskList. i.e. tasks. + */ + public String toString() { + String output = ""; + for (int idx = 0; idx < taskNum; idx++) { + Task task = taskList.get(idx); + output += ((idx + 1) + "." + task.toString() + "\n"); + } + return output.substring(0, output.length() - 1); + } + + /** + * Resets the entire list and start fresh. + */ + public void reset() { + taskList = new ArrayList(); + } + + /** + * Converts data in taskList to the appropriate String format to be stored in text file. + * @return String text. + */ + public String toText() { + String output = ""; + if (taskNum != 0) { + for (int index = 0; index < taskNum; index++) { + Task task = getTask(index); + output += (task.toString() + "\n"); + } + return output.substring(0, output.length() - 1); + } else { + return output; + } + } +} + + diff --git a/src/main/java/task/TaskStub.java b/src/main/java/task/TaskStub.java new file mode 100644 index 00000000..9229d67a --- /dev/null +++ b/src/main/java/task/TaskStub.java @@ -0,0 +1,23 @@ +package task; + +/** + * Used for testing purposes. + */ +public class TaskStub extends Task { + public TaskStub(String description) { + super(description); + super.isDone = true; + } + + public String getStatusIcon() { + return (isDone ? "+" : "-"); //+ if done, else - + } + + public void markAsDone() { + this.isDone = true; + } + + public String toString() { + return taskDesc; + } +} \ No newline at end of file diff --git a/src/main/java/task/Todo.java b/src/main/java/task/Todo.java new file mode 100644 index 00000000..e11f4151 --- /dev/null +++ b/src/main/java/task/Todo.java @@ -0,0 +1,19 @@ +package task; + +import exception.DukeException; +import task.Task; + +/** + * Extends Task. Has a task name. + */ +public class Todo extends Task { + public Todo(String description) throws DukeException { + super(description); + } + + @Override + public String toString() { + String output = "[T][" + super.getStatus() + "]" + " " + super.taskDesc; + return output; + } +} \ No newline at end of file diff --git a/src/main/java/ui/Ui.java b/src/main/java/ui/Ui.java new file mode 100644 index 00000000..cb1d0420 --- /dev/null +++ b/src/main/java/ui/Ui.java @@ -0,0 +1,148 @@ +package ui; + +import command.ViewScheduleCommand; +import task.Task; +import task.TaskList; + +import java.util.Scanner; + +/** + * Determines what is displayed to user. + */ +public class Ui { + Scanner sc = new Scanner(System.in); + + /** + * Calls when execute method of ExitCommand is called. + */ + public void showGoodbye() { + System.out.println("Bye. Hope to see you again soon!"); + } + + /** + * Prints border. + */ + public void showLine() { + String output = ""; + for (int n = 0; n < 50; n++) { + output += "_"; + } + System.out.println(output); + } + + /** + * Calls when a task is entered by user. + * Calls when execute of AddTask is called. + * @param newTask task entered. + * @param taskNum number of tasks in Task List. + */ + public void readTask(Task newTask, int taskNum) { + System.out.println("Got it. I've added this task:"); + System.out.println(newTask.toString()); + System.out.println("Now you have " + taskNum + " tasks in the list."); + } + + /** + * Displays delete message. + * Calls when execute of DeleteCommand is called. + * @param removeTask for task to be removed. + * @param taskNum number of tasks in the Task List. + */ + public void readDelete(Task removeTask, int taskNum) { + System.out.println("Noted. I've removed this task:"); + System.out.println(removeTask.toString()); + System.out.println("Now you have " + taskNum + " tasks in the list."); + } + + /** + * Displays message when a user finishes a task. + * Calls when execute of EditCommand is called. + * @param completeTask Task which has been marked as done. + */ + public void readDone(Task completeTask) { + System.out.println("Nice! I've marked this task as done:"); + System.out.println(completeTask.toString()); + } + + /** + * Displays contents of Task List. + * Calls when execute of ListCommand is called. + * @param tasks TaskList + */ + public void readList(TaskList tasks) { + System.out.println("Here are the task(s) in your list: "); + System.out.println(tasks); + } + + /** + * Reads user input. + * @return String to be parsed by parser. + */ + public String readCommand() { + return sc.nextLine(); + } + + /** + * Displays message when DukeException is caught. + * @param errorMsg DukeException e.getMessage() + */ + public void showError(String errorMsg) { + System.out.println("Your error message: " + errorMsg); + } + + /** + * Calls when Duke Exception is thrown when instantiating Task List and/ or Storage Objects. + * Calls by run method in Duke class. + */ + public void showLoadingError() { + System.out.println("Loading Error!"); + } + + /** + * Displays matching Tasks. + * Calls when execute method of FindCommand is called. + * @param tasks TaskList of tasks with keyword. + */ + public void showMatches(TaskList tasks) { + System.out.println("Here are the matching task(s) in your list: "); + System.out.println(tasks); + } + + /** + * Displays tasks in the form of a schedule e.g., view the schedule for a specific date + * Calls when execute method of ViewScheduleCommand is called. + * @param tasks TaskList of tasks with schedule. + */ + public void showSchedule(TaskList tasks) { + System.out.println("Here is the schedule for the list of task(s) on the mentioned date: "); + System.out.println(tasks); + } + + /** + * Displays all tasks with schedule. + * Calls when execute method of ViewScheduleCommand is called. + * @param tasks TaskList of tasks with schedule. + */ + public void showAllSchedule(TaskList tasks) { + System.out.println("Here is the list of task(s) that has schedule: "); + System.out.println(tasks); + } + + /** + * Displays the full set of instructions to the user so that user able to see all commands available in one view. + */ + public void readInstruction() { + System.out.println("This is the list of commands available currently. Please replace the details in ()."); + System.out.println("\n1. todo (details)"); + System.out.println("\n2. deadline (details) /by (date)d/mm/yyyy (time)HHmm."); + System.out.println("\n3. event (details) /at (date)d/mm/yyyy (start time)HHmm-(end time)HHmm."); + System.out.println("\n4. list -- This will show the list of tasks you have on hand."); + System.out.println("\n5. done (Key in the index number of the task that you have completed)."); + System.out.println("\n6. delete (Key in the index number of the task that you wish to delete)."); + System.out.println("\n7. find (Key in the keyword that you wish to search in the list of the task)."); + System.out.println("\n8. view (Key in the specific date to view the tasks you have in the schedule)."); + System.out.println("\n9. view all -- This will display all the tasks with schedule."); + System.out.println("\n10. bye -- To close off the application and save the tasks in tasks.txt file."); + System.out.println("\nHope this helps!"); + } +} \ No newline at end of file diff --git a/src/main/resources/fonts/AidaSerifaCondensed.ttf b/src/main/resources/fonts/AidaSerifaCondensed.ttf new file mode 100644 index 00000000..e5b98b12 Binary files /dev/null and b/src/main/resources/fonts/AidaSerifaCondensed.ttf differ diff --git a/src/main/resources/fonts/UniversCondensed.ttf b/src/main/resources/fonts/UniversCondensed.ttf new file mode 100644 index 00000000..ca37e7db Binary files /dev/null and b/src/main/resources/fonts/UniversCondensed.ttf differ diff --git a/src/main/resources/images/AdminDUKE.png b/src/main/resources/images/AdminDUKE.png new file mode 100644 index 00000000..337b996f Binary files /dev/null and b/src/main/resources/images/AdminDUKE.png differ diff --git a/src/main/resources/images/UserYAN.png b/src/main/resources/images/UserYAN.png new file mode 100644 index 00000000..a5fa1b0a Binary files /dev/null and b/src/main/resources/images/UserYAN.png differ diff --git a/src/main/resources/images/notebackground.jpg b/src/main/resources/images/notebackground.jpg new file mode 100644 index 00000000..05f631c1 Binary files /dev/null and b/src/main/resources/images/notebackground.jpg differ diff --git a/src/main/resources/view/DialogBox.fxml b/src/main/resources/view/DialogBox.fxml new file mode 100644 index 00000000..a49c7afe --- /dev/null +++ b/src/main/resources/view/DialogBox.fxml @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/view/MainWindow.fxml b/src/main/resources/view/MainWindow.fxml new file mode 100644 index 00000000..11726a3e --- /dev/null +++ b/src/main/resources/view/MainWindow.fxml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + +