diff --git a/.gitignore b/.gitignore index 2873e189e1..de96b25368 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,6 @@ bin/ /text-ui-test/ACTUAL.TXT text-ui-test/EXPECTED-UNIX.TXT + +# Ignore the devon_tasks.txt file in the data directory +/data/devon_tasks.txt \ No newline at end of file diff --git a/README.md b/README.md index 90aa7f092a..089dc0e738 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@ Prerequisites: JDK 17, update Intellij to the most recent version. 1. If there are any further prompts, accept the defaults. 1. Configure the project to use **JDK 17** (not other versions) as explained in [here](https://www.jetbrains.com/help/idea/sdk.html#set-up-jdk).
In the same dialog, set the **Project language level** field to the `SDK default` option. -3. After that, locate the `src/main/java/Duke.java` file, right-click it, and choose `Run Duke.main()` (if the code editor is showing compile errors, try restarting the IDE). If the setup is correct, you should see something like the below as the output: +3. After that, locate the `src/main/java/Devon.java` file, right-click it, and choose `Run Devon.main()` (if the code editor is showing compile errors, try restarting the IDE). If the setup is correct, you should see something like the below as the output: ``` Hello from ____ _ @@ -22,3 +22,8 @@ Prerequisites: JDK 17, update Intellij to the most recent version. | |_| | |_| | < __/ |____/ \__,_|_|\_\___| ``` + +## Disclaimer + +I wrote all Javadoc comments by myself, then pasted them into ChatGPT to enhance and ensure correctness. +All other work here is my own. \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..87f6c83f6a --- /dev/null +++ b/build.gradle @@ -0,0 +1,61 @@ +plugins { + id 'java' + id 'application' + id 'checkstyle' + id 'com.github.johnrengelman.shadow' version '7.1.2' +} + +repositories { + mavenCentral() +} + +dependencies { + testImplementation group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.10.0' + testRuntimeOnly group: 'org.junit.jupiter', name: 'junit-jupiter-engine', version: '5.10.0' + + String javaFxVersion = '17.0.7' + + 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' +} + +test { + useJUnitPlatform() + + testLogging { + events "passed", "skipped", "failed" + + showExceptions true + exceptionFormat "full" + showCauses true + showStackTraces true + showStandardStreams = false + } +} + +application { + mainClass.set("devon.Launcher") +} + +shadowJar { + archiveBaseName = "devon" + archiveClassifier = null +} + +run { + standardInput = System.in +} + +checkstyle { + toolVersion = '10.2' +} \ No newline at end of file diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 0000000000..eb761a9b9a --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,434 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml new file mode 100644 index 0000000000..39efb6e4ac --- /dev/null +++ b/config/checkstyle/suppressions.xml @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/docs/README.md b/docs/README.md index 47b9f984f7..17c43c86f8 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,30 +1,127 @@ -# Duke User Guide +# Devon User Guide -// Update the title above to match the actual product name +![Devon Chatbot Screenshot](Ui.png) -// Product screenshot goes here +Devon is an interactive chatbot designed to help you manage tasks +efficiently. It supports task creation, categorization, marking +tasks as done, and more, all with an engaging personality. -// Product intro goes here +## Adding todos + +To add a todo task, simply provide the keyword `todo` followed by +the task description. Devon will add this to the list. + +Example: `todo ` + +Expected output: +``` +Got it. I've added this task: + [T][] +Now you have tasks in the list. +``` ## Adding deadlines -// Describe the action and its outcome. +To add a deadline task, simply provide the keyword `deadline` +followed by the task description, the command `/by`, and the +deadline date and time, in `YYYY-MM-DD HHmm` format. +Devon will add this to the list. + +Example: `deadline /by ` + +Expected output: +``` +Got it. I've added this task: + [D][] (by: ) +Now you have tasks in the list. +``` + +## Adding events + +To add an event task, simply provide the keyword `event` +followed by the task description, the command `/from`, the +start date and time of the event in `YYYY-MM-DD HHmm`, the +command `/to`, and the end date and time of the event in +`YYYY-MM-DD HHmm` format. Devon will add this to the list. + +Example: `event /from /to ` + +Expected output: +``` +Got it. I've added this task: + [E][] (from: to: ) +Now you have tasks in the list. +``` + +## Delete task -// Give examples of usage +To delete a task, simply provide the keyword `delete` followed +by the task number of the event. If an invalid number is provided, +Devon will remind you that it is invalid. -Example: `keyword (optional arguments)` +Example: `delete 1` -// A description of the expected outcome goes here +Expected output: +``` +Noted. I've removed this task: + [T][] +Now you have tasks in the list. +``` + +## View all tasks + +To view all tasks, simply provide the keyword `list`, and Devon will +display all tasks you currently have. + +Example: `list` + +Expected output: +``` +Here are the tasks in your list: +1. [T][] +2. ... +``` +## Mark task as done + +To mark a task as done, simply provide the keyword `mark` followed +by the task number of the event. If an invalid number is provided, +Devon will remind you that it is invalid. + +Example: `mark 1` + +Expected output: ``` -expected output +Nice! I've marked this task as done: + [T][] ``` -## Feature ABC +## Mark task as undone (a.k.a unmark task) + +To mark a task as undone, simply provide the keyword `unmark` +followed by the task number of the event. If an invalid number +is provided, Devon will remind you that it is invalid. + +Example: `unmark 1` + +Expected output: +``` +OK, I've marked this task as not done yet: + [T][] +``` -// Feature details +## Shortform commands to create tasks +The full-length keywords to create tasks are `todo`, +`deadline` and `event`. However, the user can use the +keywords `t`, `d` and `e` respectively to achieve the +same results. -## Feature XYZ +Example (todo): `t ` +Example (deadline): `d /by ` -// Feature details \ No newline at end of file +Expected output: +Same as the output for +- [Adding todos](#adding-todos) +- [Adding deadlines](#adding-deadlines) +- [Adding events](#adding-events) diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..98e03ff20a Binary files /dev/null and b/docs/Ui.png differ diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..033e24c4cd 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 0000000000..66c01cfeba --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.2-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000000..fcb6fca147 --- /dev/null +++ b/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original 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 POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# 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 ;; #( + MSYS* | 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# 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"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000000..6689b85bee --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@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=. +@rem This is normally unused +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% equ 0 goto execute + +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 execute + +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 + +: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 %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/java/Duke.java b/src/main/java/Duke.java deleted file mode 100644 index 5d313334cc..0000000000 --- a/src/main/java/Duke.java +++ /dev/null @@ -1,10 +0,0 @@ -public class Duke { - public static void main(String[] args) { - String logo = " ____ _ \n" - + "| _ \\ _ _| | _____ \n" - + "| | | | | | | |/ / _ \\\n" - + "| |_| | |_| | < __/\n" - + "|____/ \\__,_|_|\\_\\___|\n"; - System.out.println("Hello from\n" + logo); - } -} diff --git a/src/main/java/devon/Deadline.java b/src/main/java/devon/Deadline.java new file mode 100644 index 0000000000..de91003f58 --- /dev/null +++ b/src/main/java/devon/Deadline.java @@ -0,0 +1,57 @@ +package devon; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Represents a task that is a deadline. + * A Deadline object corresponds to a task represented by a + * description, and a due date/time that the task needs to be completed by. + */ + +public class Deadline extends Task { + private final LocalDateTime by; + + /** + * Constructs a new Deadline object. + * + * @param description A description of the task. + * @param by The due date and time by which the task should be completed. + */ + public Deadline(String description, LocalDateTime by) { + super(description); + this.by = by; + } + + /** + * Converts the due date and time into a more readable string format. + * + * @return A string representing the due date/time in the format "MMM d yyyy, h:mm a". + */ + private String byToString() { + return by.format(DateTimeFormatter.ofPattern("MMM d yyyy, h:mm a")); + } + + /** + * Provides a string representation of the "Deadline" task in a format suitable for database storage. + * The format is "Deadline|status|description|by", where status is 1 if the task + * is done, otherwise 0. + * + * @return A string representation of the Deadline for database storage. + */ + @Override + public String dbReadableFormat() { + return String.format("Deadline|%d|%s|%s", this.isDone ? 1 : 0, this.description, this.by); + } + + /** + * Returns the string representation of the Deadline object, + * which includes the task type, status, description, and due date/time. + * + * @return A string representation of the Deadline object. + */ + @Override + public String toString() { + return "[D]" + super.toString() + " (by: " + byToString() + ")"; + } +} diff --git a/src/main/java/devon/Devon.java b/src/main/java/devon/Devon.java new file mode 100644 index 0000000000..90143ef341 --- /dev/null +++ b/src/main/java/devon/Devon.java @@ -0,0 +1,313 @@ +package devon; + +import java.io.IOException; +import java.time.LocalDateTime; +import java.time.format.DateTimeParseException; +import java.util.ArrayList; +import java.util.Scanner; + +/** + * Represents the Devon bot, which manages a task list. + * Devon can add, delete, mark, unmark tasks, and save/load tasks from a database. + */ +public class Devon { + + protected Scanner scanner = new Scanner(System.in); + private final TaskList tasks = new TaskList(); + private final Storage storage = new Storage(); + private final Parser parser = new Parser(); + private final Ui ui = new Ui(); + + /** + * Enum to represent the various commands the user can input. + */ + private enum Command { + BYE, LIST, MARK, UNMARK, TODO, T, DEADLINE, D, EVENT, E, DELETE, FIND, UNKNOWN; + + /** + * Converts a string command to the corresponding enum value. + * + * @param command The command string input by the user. + * @return The corresponding Command enum value. + */ + public static Command fromStringToEnum(String command) { + try { + return Command.valueOf(command.toUpperCase()); + } catch (IllegalArgumentException e) { + return UNKNOWN; + } + } + } + + /** + * Starts the Devon bot. Loads tasks from the database, receives user input, and saves tasks back to the database. + */ + protected void start() { + ArrayList stringListOfTasks = storage.loadTasksFromDatabase(); + try { + tasks.initialiseLoadTasks(stringListOfTasks); + } catch (DevonReadDatabaseException e) { + ui.displayException(e); + } + } + + /** + * Displays the introduction message to the user. + */ + protected String introduction() { + return "\t" + "Hello! I'm Devon.\n" + "\t" + "What can I do for you?"; + } + + /** + * Displays the goodbye message to the user. + */ + private String goodbye() { + try { + storage.saveTasksToDatabase(tasks); + } catch (IOException e) { + ui.displayText("Error! Task(s) could not be saved."); + } + return "\t" + "Bye. Hope to see you again soon!"; + } + + /** + * Continuously receives user input until the "BYE" command is given. + * Based on the input, different actions are performed. + */ + protected String getResponse(String input) { + Command command = Command.fromStringToEnum(parser.extractCommand(input)); + + try { + switch (command) { + case BYE: + return goodbye(); + case LIST: + return getListAsString(); + case MARK: + return markAction(input); + case UNMARK: + return unmarkAction(input); + case TODO: + case T: + return todoAction(input); + case DEADLINE: + case D: + return deadlineAction(input); + case EVENT: + case E: + return eventAction(input); + case DELETE: + return deleteAction(input); + case FIND: + return findAction(input); + default: + unknownAction(); + } + } catch (DevonException e) { + return e.toString(); + } + return "Error"; + } + + /** + * Marks a task as done based on user input. + * + * @param input The user input specifying which task to mark as done. + * @throws DevonInvalidTaskNumberException If the task number provided is invalid. + */ + private String markAction(String input) throws DevonInvalidTaskNumberException { + int taskIndex; + try { + taskIndex = parser.extractTaskIndex(input) - 1; + } catch (NumberFormatException e) { + throw new DevonInvalidTaskNumberException(); + } + if (taskIndex < 0 || taskIndex >= tasks.getNumberOfTasks()) { + throw new DevonInvalidTaskNumberException(); + } + return markAsDone(taskIndex); + } + + /** + * Marks a task as undone based on user input. + * + * @param input The user input specifying which task to mark as undone. + * @throws DevonInvalidTaskNumberException If the task number provided is invalid. + */ + private String unmarkAction(String input) throws DevonInvalidTaskNumberException { + int taskIndex; + + try { + taskIndex = parser.extractTaskIndex(input) - 1; + } catch (NumberFormatException e) { + throw new DevonInvalidTaskNumberException(); + } + if (taskIndex < 0 || taskIndex >= tasks.getNumberOfTasks()) { + throw new DevonInvalidTaskNumberException(); + } + + return markAsUndone(taskIndex); + } + + /** + * Adds a new Todo task to the list based on user input. + * + * @param input The user input specifying the description of the Todo task. + */ + private String todoAction(String input) { + String description = parser.extractTodo(input); + return addToList(new Todo(description)); + } + + /** + * Adds a new Deadline task to the list based on user input. + * + * @param input The user input specifying the description and due date of the Deadline task. + * @throws DevonInvalidDeadlineException If the deadline format is invalid. + * @throws DevonInvalidDateTimeException If the date/time format is invalid. + */ + private String deadlineAction(String input) throws DevonInvalidDeadlineException, DevonInvalidDateTimeException { + String[] contents = parser.extractDeadline(input); + String description = contents[0]; + String by = contents[1]; + + assert description != null && !description.isEmpty() : "Deadline description cannot be empty."; + assert by != null && !by.isEmpty() : "Deadline date cannot be empty."; + + try { + LocalDateTime byDateTime = LocalDateTime.parse(by, Storage.DATE_TIME_FORMATTER_FOR_EXTERNAL_INPUT); + return addToList(new Deadline(description, byDateTime)); + } catch (DateTimeParseException e) { + throw new DevonInvalidDateTimeException(); + } + } + + /** + * Adds a new Event task to the list based on user input. + * + * @param input The user input specifying the description, start time, and end time of the Event task. + * @throws DevonInvalidEventException If the event format is invalid. + * @throws DevonInvalidDateTimeException If the date/time format is invalid. + */ + private String eventAction(String input) throws DevonInvalidEventException, DevonInvalidDateTimeException { + String[] contents = parser.extractEvent(input); + String description = contents[0]; + String from = contents[1]; + String to = contents[2]; + + assert description != null && !description.isEmpty() : "Event description cannot be empty."; + assert from != null && !from.isEmpty() : "Event start time cannot be empty."; + assert to != null && !to.isEmpty() : "Event end time cannot be empty."; + + try { + LocalDateTime fromDateTime = LocalDateTime.parse(from, Storage.DATE_TIME_FORMATTER_FOR_EXTERNAL_INPUT); + LocalDateTime toDateTime = LocalDateTime.parse(to, Storage.DATE_TIME_FORMATTER_FOR_EXTERNAL_INPUT); + return addToList(new Event(description, fromDateTime, toDateTime)); + } catch (DateTimeParseException e) { + throw new DevonInvalidDateTimeException(); + } + } + + /** + * Deletes a task from the list based on user input. + * + * @param input The user input specifying which task to delete. + * @throws DevonInvalidTaskNumberException If the task number provided is invalid. + */ + private String deleteAction(String input) throws DevonInvalidTaskNumberException { + int taskIndex; + + try { + taskIndex = parser.extractTaskIndex(input) - 1; + } catch (NumberFormatException e) { + throw new DevonInvalidTaskNumberException(); + } + + if (taskIndex < 0 || taskIndex >= tasks.getNumberOfTasks()) { + throw new DevonInvalidTaskNumberException(); + } + + return deleteTask(taskIndex); + } + + /** + * Finds and displays tasks that match a given keyword. + *

+ * This method extracts the content from the provided input string, converts it to lowercase, and searches + * for matching tasks within the task list. The results are then displayed to the user. + * + * @param input The input string containing the keyword for searching tasks. + */ + private String findAction(String input) { + String keyword = parser.extractContent(input).toLowerCase(); + String results = tasks.search(keyword); + return "Here are the matching tasks in your list:\n\t" + results; + } + + /** + * Handles the case where the user inputs an unknown command. + * + * @throws DevonUnknownCommandException If the command is unknown. + */ + private void unknownAction() throws DevonUnknownCommandException { + throw new DevonUnknownCommandException(); + } + + /** + * Adds a task to the task list and displays a confirmation message. + * + * @param task The task to add to the list. + */ + private String addToList(Task task) { + tasks.addTask(task); + return "\t" + "Got it. I've added this task:\n\t\t" + + task + "\n\tNow you have " + + tasks.getNumberOfTasks() + + " tasks in the list."; + } + + /** + * Prints the current task list to the user. + */ + private String getListAsString() { + return tasks.getListAsString(); + } + + /** + * Marks a task as done and displays a confirmation message. + * + * @param taskIndex The index of the task to mark as done. + */ + private String markAsDone(int taskIndex) { + return tasks.markAsDone(taskIndex); + } + + /** + * Marks a task as undone and displays a confirmation message. + * + * @param taskIndex The index of the task to mark as undone. + */ + private String markAsUndone(int taskIndex) { + return tasks.markAsUndone(taskIndex); + } + + /** + * Deletes a task from the list and displays a confirmation message. + * + * @param taskIndex The index of the task to delete. + */ + private String deleteTask(int taskIndex) { + String textResponse = tasks.removeTask(taskIndex); + return textResponse + "\n\tNow you have " + tasks.getNumberOfTasks() + " tasks in the list."; + } + + /** + * Main method to start the Devon bot. + * + * @param args Command-line arguments (not used). + */ + public static void main(String[] args) { + Devon bot = new Devon(); + bot.start(); + } +} diff --git a/src/main/java/devon/DevonException.java b/src/main/java/devon/DevonException.java new file mode 100644 index 0000000000..68990955d5 --- /dev/null +++ b/src/main/java/devon/DevonException.java @@ -0,0 +1,19 @@ +package devon; + + +/** + * Represents a base exception for the Devon application. + * This is an abstract class that serves as a common parent for all exceptions related to Devon. + */ +public abstract class DevonException extends Exception { + + /** + * Returns a default string representation of the exception. + * + * @return A string indicating an error occurred: "OOPS!!!". + */ + @Override + public String toString() { + return "OOPS!!!"; + } +} diff --git a/src/main/java/devon/DevonInvalidDateTimeException.java b/src/main/java/devon/DevonInvalidDateTimeException.java new file mode 100644 index 0000000000..aa161ab20b --- /dev/null +++ b/src/main/java/devon/DevonInvalidDateTimeException.java @@ -0,0 +1,22 @@ +package devon; + +/** + * Exception thrown when there is an invalid date-time format in the Devon application. + * This exception is a specific type of {@link DevonException} used to indicate errors + * related to date-time parsing. + */ +public class DevonInvalidDateTimeException extends DevonException { + + /** + * Returns a detailed string representation of the exception, including the specific + * error message related to invalid date-time formats. + * + * @return A string indicating the error: "OOPS!!! Invalid date-time format for '/from' or '/to'. + * Please use 'yyyy-MM-dd HHmm'." + */ + @Override + public String toString() { + return super.toString() + " Invalid date-time format for '/from' or '/to'. Please use 'yyyy-MM-dd HHmm'."; + } +} + diff --git a/src/main/java/devon/DevonInvalidDeadlineException.java b/src/main/java/devon/DevonInvalidDeadlineException.java new file mode 100644 index 0000000000..24bacef80c --- /dev/null +++ b/src/main/java/devon/DevonInvalidDeadlineException.java @@ -0,0 +1,20 @@ +package devon; + +/** + * Exception thrown when there is an invalid deadline format in the Devon application. + * This exception is a specific type of {@link DevonException} used to indicate errors + * related to deadline parsing. + */ +public class DevonInvalidDeadlineException extends DevonException { + + /** + * Returns a detailed string representation of the exception, including the specific + * error message related to invalid deadline formats. + * + * @return A string indicating the error: "OOPS!!! Deadline is invalid! Usage: deadline [task] /by [deadline]". + */ + @Override + public String toString() { + return super.toString() + " Deadline is invalid! Usage: deadline [task] /by [deadline]"; + } +} diff --git a/src/main/java/devon/DevonInvalidEventException.java b/src/main/java/devon/DevonInvalidEventException.java new file mode 100644 index 0000000000..0ae5244b70 --- /dev/null +++ b/src/main/java/devon/DevonInvalidEventException.java @@ -0,0 +1,21 @@ +package devon; + +/** + * Exception thrown when there is an invalid event format in the Devon application. + * This exception is a specific type of {@link DevonException} used to indicate errors + * related to event parsing. + */ +public class DevonInvalidEventException extends DevonException { + + /** + * Returns a detailed string representation of the exception, including the specific + * error message related to invalid event formats. + * + * @return A string indicating the error: + * "OOPS!!! Event is invalid! Usage: event [task] /from [start_time] /to [end_time]". + */ + @Override + public String toString() { + return super.toString() + " Event is invalid! Usage: event [task] /from [start_time] /to [end_time]"; + } +} diff --git a/src/main/java/devon/DevonInvalidTaskNumberException.java b/src/main/java/devon/DevonInvalidTaskNumberException.java new file mode 100644 index 0000000000..60583d3ac2 --- /dev/null +++ b/src/main/java/devon/DevonInvalidTaskNumberException.java @@ -0,0 +1,20 @@ +package devon; + +/** + * Exception thrown when a task number is invalid or not found in the Devon application. + * This exception is a specific type of {@link DevonException} used to indicate errors + * related to task number handling. + */ +public class DevonInvalidTaskNumberException extends DevonException { + + /** + * Returns a detailed string representation of the exception, including the specific + * error message related to invalid task numbers. + * + * @return A string indicating the error: "OOPS!!! Task not found!". + */ + @Override + public String toString() { + return super.toString() + " Task not found!"; + } +} diff --git a/src/main/java/devon/DevonReadDatabaseException.java b/src/main/java/devon/DevonReadDatabaseException.java new file mode 100644 index 0000000000..86798e0b2c --- /dev/null +++ b/src/main/java/devon/DevonReadDatabaseException.java @@ -0,0 +1,20 @@ +package devon; + +/** + * Exception thrown when there is an error reading from the database in the Devon application. + * This exception is a specific type of {@link DevonException} used to indicate issues + * related to database reading operations. + */ +public class DevonReadDatabaseException extends DevonException { + + /** + * Returns a detailed string representation of the exception, including the specific + * error message related to database reading failures. + * + * @return A string indicating the error: "OOPS!!! Unable to read database!". + */ + @Override + public String toString() { + return super.toString() + " Unable to read database!"; + } +} diff --git a/src/main/java/devon/DevonUnknownCommandException.java b/src/main/java/devon/DevonUnknownCommandException.java new file mode 100644 index 0000000000..5abef95e71 --- /dev/null +++ b/src/main/java/devon/DevonUnknownCommandException.java @@ -0,0 +1,20 @@ +package devon; + +/** + * Exception thrown when an unknown or unrecognized command is encountered in the Devon application. + * This exception is a specific type of {@link DevonException} used to indicate errors + * related to invalid commands input by the user. + */ +public class DevonUnknownCommandException extends DevonException { + + /** + * Returns a detailed string representation of the exception, including the specific + * error message related to unknown commands. + * + * @return A string indicating the error: "OOPS!!! Unknown command!". + */ + @Override + public String toString() { + return super.toString() + " Unknown command!"; + } +} diff --git a/src/main/java/devon/DialogBox.java b/src/main/java/devon/DialogBox.java new file mode 100644 index 0000000000..2906f78cbb --- /dev/null +++ b/src/main/java/devon/DialogBox.java @@ -0,0 +1,60 @@ +package devon; + +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; + +/** + * 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); + } + + /** + * 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); + } + + public static DialogBox getUserDialog(String text, Image img) { + return new DialogBox(text, img); + } + + public static DialogBox getDevonDialog(String text, Image img) { + var db = new DialogBox(text, img); + db.flip(); + return db; + } +} diff --git a/src/main/java/devon/Event.java b/src/main/java/devon/Event.java new file mode 100644 index 0000000000..1934cae824 --- /dev/null +++ b/src/main/java/devon/Event.java @@ -0,0 +1,70 @@ +package devon; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Represents an "Event" task in the Devon application. + * An "Event" task has a description and a time range indicating the start and end times of the event. + */ +public class Event extends Task { + private LocalDateTime from; + private LocalDateTime to; + + /** + * Constructs a new "Event" task with the specified description, start time, and end time. + * The task is initially marked as not done. + * + * @param description A brief description of the "Event" task. + * @param from The start time of the event. + * @param to The end time of the event. + */ + public Event(String description, LocalDateTime from, LocalDateTime to) { + super(description); + this.from = from; + this.to = to; + } + + /** + * Provides a string representation of the "Event" task in a format suitable for database storage. + * + * @return A string representing the "Event" task in a format suitable for database storage, + * with the format "Event|<status>|<description>|<from>|<to>", + * where <status> is 1 if done, 0 if not done, <from> is the start time of the event, + * and <to> is the end time of the event. + */ + @Override + public String dbReadableFormat() { + return String.format("Event|%d|%s|%s|%s", this.isDone ? 1 : 0, this.description, this.from, this.to); + } + + /** + * Converts the start date and time of the event to a formatted string. + * + * @return A string representing the start date and time of the event in the format "MMM d yyyy, h:mm a". + */ + private String fromToString() { + return from.format(DateTimeFormatter.ofPattern("MMM d yyyy, h:mm a")); + } + + /** + * Converts the end date and time of the event to a formatted string. + * + * @return A string representing the end date and time of the event in the format "MMM d yyyy, h:mm a". + */ + private String toToString() { + return to.format(DateTimeFormatter.ofPattern("MMM d yyyy, h:mm a")); + } + + /** + * Returns a string representation of the "Event" task for display purposes. + * + * @return A string representing the "Event" task, including its status icon, description, start time, and end time, + * with the format "[E][status] description (from: start_time to: end_time)", + * where [status] is "X" if done, " " if not done. + */ + @Override + public String toString() { + return "[E]" + super.toString() + " (from: " + fromToString() + " to: " + toToString() + ")"; + } +} diff --git a/src/main/java/devon/Launcher.java b/src/main/java/devon/Launcher.java new file mode 100644 index 0000000000..7c4fc4e8ab --- /dev/null +++ b/src/main/java/devon/Launcher.java @@ -0,0 +1,12 @@ +package devon; + +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); + } +} diff --git a/src/main/java/devon/Main.java b/src/main/java/devon/Main.java new file mode 100644 index 0000000000..e5b1869fd6 --- /dev/null +++ b/src/main/java/devon/Main.java @@ -0,0 +1,30 @@ +package devon; +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 Devon devon = new Devon(); + + @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); + fxmlLoader.getController().setDevon(devon); // inject the Devon instance + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/devon/MainWindow.java b/src/main/java/devon/MainWindow.java new file mode 100644 index 0000000000..a6aa2406d6 --- /dev/null +++ b/src/main/java/devon/MainWindow.java @@ -0,0 +1,55 @@ +package devon; + +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; +/** + * Controller for the main GUI. + */ +public class MainWindow extends AnchorPane { + @FXML + private ScrollPane scrollPane; + @FXML + private VBox dialogContainer; + @FXML + private TextField userInput; + @FXML + private Button sendButton; + + private Devon devon; + + private Image userImage = new Image(this.getClass().getResourceAsStream("/images/DaUser.png")); + private Image devonImage = new Image(this.getClass().getResourceAsStream("/images/DaDevon.png")); + + @FXML + public void initialize() { + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + } + + /** Injects the Devon instance */ + public void setDevon(Devon devon) { + this.devon = devon; + devon.start(); + dialogContainer.getChildren().add(DialogBox.getDevonDialog(devon.introduction(), devonImage)); + } + + /** + * 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 = devon.getResponse(input); + dialogContainer.getChildren().addAll( + DialogBox.getUserDialog(input, userImage), + DialogBox.getDevonDialog(response, devonImage) + ); + userInput.clear(); + } +} + diff --git a/src/main/java/devon/Parser.java b/src/main/java/devon/Parser.java new file mode 100644 index 0000000000..190cf1485a --- /dev/null +++ b/src/main/java/devon/Parser.java @@ -0,0 +1,94 @@ +package devon; + +import java.util.Arrays; + +/** + * Parses user input to extract commands and relevant details for task management. + * Handles extraction of different task-related information from user input strings. + */ +public class Parser { + public Parser() { } + + /** + * Extracts the command from a user input message. + * + * @param msg The input message containing the command. + * @return The command extracted from the input message. + */ + protected String extractCommand(String msg) { + String[] parts = msg.split(" "); + return parts[0]; + } + + /** + * Extracts the content from a user input message after the command. + * + * @param input The input message containing the command and content. + * @return The content of the message after the command, or "Error" if no content is found. + */ + protected String extractContent(String input) { + String[] parts = input.split(" "); + return parts.length > 1 + ? String.join(" ", Arrays.copyOfRange(parts, 1, parts.length)) + : "Error"; + } + + /** + * Extracts the task index from the user input. + * + * @param input The input message containing the task index. + * @return The task index extracted from the input. + * @throws NumberFormatException If the task index is not a valid integer. + */ + protected int extractTaskIndex(String input) throws NumberFormatException { + return Integer.parseInt(extractContent(input)); + } + + /** + * Extracts the description for a Todo task from the user input. + * + * @param input The input message containing the Todo task description. + * @return The description of the Todo task. + */ + protected String extractTodo(String input) { + return extractContent(input).trim(); + } + + /** + * Extracts the description and deadline from the user input for a Deadline task. + * + * @param input The input message containing the Deadline task details. + * @return An array containing the description and deadline for the Deadline task. + * @throws DevonInvalidDeadlineException If the input does not contain the "/by" keyword. + */ + protected String[] extractDeadline(String input) throws DevonInvalidDeadlineException { + String content = extractContent(input); + if (!content.contains("/by")) { + throw new DevonInvalidDeadlineException(); + } + String[] parts = content.split("/by", 2); + String description = parts[0].trim(); + String by = parts[1].trim(); + return new String[]{ description, by }; + } + + /** + * Extracts the description, start date and time, and end date and time from the user input for an Event task. + * + * @param input The input message containing the Event task details. + * @return An array containing the description, start date and time, and end date and time for the Event task. + * @throws DevonInvalidEventException If the input does not contain both "/from" and "/to" keywords. + */ + protected String[] extractEvent(String input) throws DevonInvalidEventException { + String content = extractContent(input); + if (!(content.contains("/from") && content.contains("/to"))) { + throw new DevonInvalidEventException(); + } + String[] partsFrom = content.split("/from", 2); + String[] partsTo = partsFrom[1].split("/to", 2); + String description = partsFrom[0].trim(); + String from = partsTo[0].trim(); + String to = partsTo[1].trim(); + return new String[]{ description, from, to }; + } +} diff --git a/src/main/java/devon/Storage.java b/src/main/java/devon/Storage.java new file mode 100644 index 0000000000..0149f705e1 --- /dev/null +++ b/src/main/java/devon/Storage.java @@ -0,0 +1,80 @@ +package devon; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Paths; +import java.time.format.DateTimeFormatter; +import java.util.ArrayList; +import java.util.Scanner; + +/** + * Handles loading and saving tasks to and from a file-based database. + * Manages the task database file operations, including creation and data formatting. + */ +public class Storage { + protected static final String DIRECTORY_PATH = "./data"; + protected static final String DB_PATH = String.valueOf(Paths.get(Storage.DIRECTORY_PATH, "devon_tasks.txt")); + protected static final String DB_DELIMITER = "\\|"; + + protected static final DateTimeFormatter DATE_TIME_FORMATTER_FOR_EXTERNAL_INPUT = + DateTimeFormatter.ofPattern("yyyy-MM-dd HHmm"); + protected static final DateTimeFormatter DATE_TIME_FORMATTER_FOR_DB = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm"); + + /** + * Constructs a Storage object. + */ + public Storage() { } + + /** + * Loads tasks from the database file. + * If the file does not exist, it creates a new task database file. + * + * @return An ArrayList of strings representing the tasks. + */ + protected ArrayList loadTasksFromDatabase() { + ArrayList tasks = new ArrayList<>(); + try { + Scanner fileReader = new Scanner(new File(Storage.DB_PATH)); + while (fileReader.hasNextLine()) { + tasks.add(fileReader.nextLine()); + } + fileReader.close(); + } catch (FileNotFoundException e) { + this.createTaskDatabase(); + } + return tasks; + } + + /** + * Creates a new task database file and directory if they do not exist. + */ + private void createTaskDatabase() { + new File(Storage.DIRECTORY_PATH).mkdir(); + try { + new File(Storage.DB_PATH).createNewFile(); + } catch (IOException e) { + System.out.println("Error: Cannot create database!"); + } + } + + /** + * Saves the tasks from a TaskList to the database file. + * + * @param tasks The TaskList object containing tasks to be saved. + * @throws IOException If there is an error writing to the database file. + */ + protected void saveTasksToDatabase(TaskList tasks) throws IOException { + FileWriter filewriter = new FileWriter(Storage.DB_PATH); + BufferedWriter bufferedWriter = new BufferedWriter(filewriter); + for (int i = 0; i < tasks.getNumberOfTasks(); i++) { + bufferedWriter.write(tasks.getTask(i).dbReadableFormat()); + bufferedWriter.newLine(); + } + bufferedWriter.close(); + filewriter.close(); + } +} diff --git a/src/main/java/devon/Task.java b/src/main/java/devon/Task.java new file mode 100644 index 0000000000..b057c94ccf --- /dev/null +++ b/src/main/java/devon/Task.java @@ -0,0 +1,94 @@ +package devon; + +/** + * Represents an abstract task in the Devon application. + * A task has a description and a status indicating whether it is done or not. + * Subclasses must provide their specific format for database storage. + */ +public abstract class Task { + protected String description; + protected boolean isDone; + + /** + * Constructs a new Task with the specified description. + * The task is initially marked as not done. + * + * @param description A brief description of the task. + */ + public Task(String description) { + this.description = description; + this.isDone = false; + } + + /** + * Returns the status icon of the task. + * + * @return A string representing the task status; "X" if the task is done, otherwise a space. + */ + public String getStatusIcon() { + return (isDone ? "X" : " "); // mark done task with X + } + + /** + * Returns the description of the task. + * + * @return The description of the task. + */ + public String getDescription() { + return description; + } + + /** + * Marks the task as done and returns a confirmation message. + * + * @return A string confirming that the task has been marked as done. + */ + public String markAsDone() { + isDone = true; + return "\tNice! I've marked this task as done:\n\t\t" + this; + } + + /** + * Marks the task as done without returning a message. + */ + public void markAsDoneSilently() { + isDone = true; + } + + /** + * Marks the task as not done and returns a confirmation message. + * + * @return A string confirming that the task has been marked as not done. + */ + public String markAsUndone() { + isDone = false; + return "\tOK, I've marked this task as not done yet:\n\t\t" + this; + } + + /** + * Returns a message announcing the deletion of the task, but does not actually delete the task from the TaskList. + * + * @return A string confirming that the task has been removed. + */ + public String announceDeletion() { + return "\tNoted. I've removed this task:\n\t\t" + this; + } + + /** + * Provides a string representation of the task in a format suitable for database storage. + * Subclasses must implement this method to return their specific format. + * + * @return A string representing the task in a format suitable for database storage. + */ + public abstract String dbReadableFormat(); + + /** + * Returns a string representation of the task for display purposes. + * + * @return A string representing the task, including its status icon and description. + */ + @Override + public String toString() { + return String.format("[%s] %s", getStatusIcon(), getDescription()); + } +} diff --git a/src/main/java/devon/TaskList.java b/src/main/java/devon/TaskList.java new file mode 100644 index 0000000000..537c1d1d3e --- /dev/null +++ b/src/main/java/devon/TaskList.java @@ -0,0 +1,160 @@ +package devon; + +import java.time.LocalDateTime; +import java.util.ArrayList; + +/** + * Represents a list of tasks in the Devon application. + * Provides methods to manage and manipulate the list of tasks, including adding, removing, and marking tasks. + */ +public class TaskList { + private final ArrayList tasks; + + /** + * Constructs an empty task list. + */ + public TaskList() { + this.tasks = new ArrayList<>(); + } + + /** + * Returns the number of tasks in the task list. + * + * @return The number of tasks in the list. + */ + public int getNumberOfTasks() { + return tasks.size(); + } + + /** + * Initializes the task list with tasks loaded from a database. + * + * @param stringListOfTasks A list of strings representing tasks in a database format. + * @throws DevonReadDatabaseException If there is an error reading or parsing the task data from the database. + */ + public void initialiseLoadTasks(ArrayList stringListOfTasks) throws DevonReadDatabaseException { + for (String line : stringListOfTasks) { + String[] fields = line.split(Storage.DB_DELIMITER); + Task newTask; + + switch (fields[0]) { + case "Deadline": + newTask = new Deadline( + fields[2], + LocalDateTime.parse(fields[3], Storage.DATE_TIME_FORMATTER_FOR_DB) + ); + break; + case "Event": + newTask = new Event( + fields[2], + LocalDateTime.parse(fields[3], Storage.DATE_TIME_FORMATTER_FOR_DB), + LocalDateTime.parse(fields[4], Storage.DATE_TIME_FORMATTER_FOR_DB) + ); + break; + case "Todo": + newTask = new Todo(fields[2]); + break; + default: + throw new DevonReadDatabaseException(); + } + + boolean toBeMarkedAsDone = Integer.parseInt(fields[1]) == 1; + if (toBeMarkedAsDone) { + newTask.markAsDoneSilently(); + } + + this.addTask(newTask); + } + } + + /** + * Adds a task to the task list. + * + * @param task The task to be added. + */ + protected void addTask(Task task) { + this.tasks.add(task); + } + + /** + * Retrieves a task from the task list based on the task number. + * + * @param taskNumber The index of the task to retrieve (0-based index). + * @return The task at the specified index. + */ + protected Task getTask(int taskNumber) { + return this.tasks.get(taskNumber); + } + + /** + * Removes a task from the task list based on the task number. + * + * @param taskNumber The index of the task to be removed (0-based index). + * @return A message indicating the task that was removed. + */ + protected String removeTask(int taskNumber) { + String textResponse = getTask(taskNumber).announceDeletion(); + this.tasks.remove(taskNumber); + return textResponse; + } + + /** + * Marks a task as done based on the task number. + * + * @param taskNumber The index of the task to be marked as done (0-based index). + * @return A message indicating the task that was marked as done. + */ + protected String markAsDone(int taskNumber) { + return getTask(taskNumber).markAsDone(); + } + + /** + * Marks a task as undone based on the task number. + * + * @param taskNumber The index of the task to be marked as undone (0-based index). + * @return A message indicating the task that was marked as not done. + */ + protected String markAsUndone(int taskNumber) { + return getTask(taskNumber).markAsUndone(); + } + + /** + * Returns a string representation of all tasks in the list. + * + * @return A string listing all tasks with their indices and details. + */ + protected String getListAsString() { + StringBuilder s = new StringBuilder("\t" + "Here are the tasks in your list:"); + + for (int i = 0; i < this.getNumberOfTasks(); i++) { + Task current = this.getTask(i); + String formattedEntry = String.format("\n\t" + "%d. %s", i + 1, current); + s.append(formattedEntry); + } + + return s.toString(); + } + + /** + * Searches for tasks that contain a specific keyword and returns the matching tasks as a formatted string. + *

+ * This method iterates through the list of tasks, checks if each task's description contains the specified + * keyword (case-insensitive), and collects the matching tasks. The tasks are then formatted and returned as + * a string with each task on a new line, prefixed by its position in the list. + * + * @param query The keyword to search for within the task descriptions. + * @return A formatted string of matching tasks, each task on a new line prefixed by its position in the list. + */ + protected String search(String query) { + ArrayList matchingTasks = new ArrayList<>(); + + for (int i = 0; i < getNumberOfTasks(); i++) { + Task task = getTask(i); + if (task.getDescription().toLowerCase().contains(query)) { + matchingTasks.add((i + 1) + ". " + task); + } + } + + return String.join("\n\t", matchingTasks); + } +} diff --git a/src/main/java/devon/Todo.java b/src/main/java/devon/Todo.java new file mode 100644 index 0000000000..26c0fa78b9 --- /dev/null +++ b/src/main/java/devon/Todo.java @@ -0,0 +1,41 @@ +package devon; + +/** + * Represents a "To-Do" task in the Devon application. + * A "To-Do" task has a description and a status indicating whether it is done or not. + */ +public class Todo extends Task { + + /** + * Constructs a new "To-Do" task with the specified description. + * The task is initially marked as not done. + * + * @param description A brief description of the "To-Do" task. + */ + public Todo(String description) { + super(description); + } + + /** + * Provides a string representation of the "To-Do" task in a format suitable for database storage. + * + * @return A string representing the "To-Do" task in a format suitable for database storage, + * with the format "Todo|<status>|<description>", + * where <status> is 1 if done, 0 if not done. + */ + @Override + public String dbReadableFormat() { + return String.format("Todo|%d|%s", this.isDone ? 1 : 0, this.description); + } + + /** + * Returns a string representation of the "To-Do" task for display purposes. + * + * @return A string representing the "To-Do" task, including its status icon and description, + * with the format "[T][status] description", where [status] is "X" if done, " " if not done. + */ + @Override + public String toString() { + return "[T]" + super.toString(); + } +} diff --git a/src/main/java/devon/Ui.java b/src/main/java/devon/Ui.java new file mode 100644 index 0000000000..1f5e1ac746 --- /dev/null +++ b/src/main/java/devon/Ui.java @@ -0,0 +1,41 @@ +package devon; + +/** + * Handles user interface interactions, specifically for displaying information and exceptions to the user. + */ +public class Ui { + /** + * Constructs a Ui object. + */ + public Ui() { } + + /** + * Prints a long line of underscores to separate sections of output. + */ + private void printLongLine() { + String lineSeparator = "____________________"; + System.out.println("\t" + lineSeparator); + } + + /** + * Displays an exception message to the user. + * + * @param e The exception to be displayed. + */ + protected void displayException(Exception e) { + printLongLine(); + System.out.println("\t" + e); + printLongLine(); + } + + /** + * Displays a text message to the user. + * + * @param text The text message to be displayed. + */ + protected void displayText(String text) { + printLongLine(); + System.out.println(text); + printLongLine(); + } +} diff --git a/src/main/resources/images/DaDevon.png b/src/main/resources/images/DaDevon.png new file mode 100644 index 0000000000..c5bd6c15bc Binary files /dev/null and b/src/main/resources/images/DaDevon.png differ diff --git a/src/main/resources/images/DaUser.png b/src/main/resources/images/DaUser.png new file mode 100644 index 0000000000..5fa00c965d Binary files /dev/null and b/src/main/resources/images/DaUser.png differ diff --git a/src/main/resources/view/DialogBox.fxml b/src/main/resources/view/DialogBox.fxml new file mode 100644 index 0000000000..fe672c90ea --- /dev/null +++ b/src/main/resources/view/DialogBox.fxml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + diff --git a/src/main/resources/view/MainWindow.fxml b/src/main/resources/view/MainWindow.fxml new file mode 100644 index 0000000000..001ee36210 --- /dev/null +++ b/src/main/resources/view/MainWindow.fxml @@ -0,0 +1,44 @@ + + + + + + + + + + + +