diff --git a/.github/workflows/java_ci.yml b/.github/workflows/java_ci.yml new file mode 100644 index 0000000000..391c46b4fe --- /dev/null +++ b/.github/workflows/java_ci.yml @@ -0,0 +1,34 @@ +name: Java CI + +on: [push, pull_request] + +jobs: + build: + strategy: + matrix: + platform: [ubuntu-latest, macos-latest, windows-latest] + runs-on: ${{ matrix.platform }} + + steps: + - name: Set up repository + uses: actions/checkout@master + + - name: Set up repository + uses: actions/checkout@master + with: + ref: master + + - name: Merge to master + run: git checkout --progress --force ${{ github.sha }} + + - name: Validate Gradle Wrapper + uses: gradle/wrapper-validation-action@v1 + + - name: Setup JDK 11 + uses: actions/setup-java@v1 + with: + java-version: '11' + java-package: jdk+fx + + - name: Build and check with Gradle + run: ./gradlew check diff --git a/.gitignore b/.gitignore index 2873e189e1..b8e62d3ba1 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,4 @@ bin/ /text-ui-test/ACTUAL.TXT text-ui-test/EXPECTED-UNIX.TXT +/data diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..044b1c0a13 --- /dev/null +++ b/build.gradle @@ -0,0 +1,64 @@ +plugins { + id 'java' + id 'application' + id 'com.github.johnrengelman.shadow' version '7.1.2' + id 'checkstyle' + id 'org.openjfx.javafxplugin' version '0.0.13' +} + +repositories { + mavenCentral() +} + +javafx { + version = "17" + modules = [ 'javafx.controls', 'javafx.fxml' ] +} + +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("duke.Launcher") +} + +shadowJar { + archiveBaseName = "duke" + archiveClassifier = null + dependsOn("distZip", "distTar") +} + +run{ + 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 0000000000..acac1a8e28 --- /dev/null +++ b/config/checkstyle/checkstyle.xml @@ -0,0 +1,434 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/config/checkstyle/suppressions.xml b/config/checkstyle/suppressions.xml new file mode 100644 index 0000000000..135ea49ee0 --- /dev/null +++ b/config/checkstyle/suppressions.xml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/docs/README.md b/docs/README.md index 8077118ebe..bcb6353daf 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,29 +1,121 @@ -# User Guide +# Changoose +Changoose is a task manager that helps you keep track of your tasks, deadlines and events. +With a simple and intuitive interface, Changoose ensures that you never miss out on any important +tasks or events ever again! -## Features +## Features +> **Notes on the commands format** +> +> Words in `UPPER_CASE` are the parameters to be supplied by the ***user***. +> e.g. in `todo TASK NAME`, `TASK NAME` is a parameter which can be used, like `todo tutorial x`. + +### 1. Task Management +- **Add a Task** +- **List Tasks** +- **Mark Task as Done** +- **Unmark Task as Not Done** +- **Delete a Task** +- **Find a Task** -### Feature-ABC +### 2. Persistent Storage +- Changoose keeps your Tasks ~~safe~~ **saved**! -Description of the feature. +## Usage -### Feature-XYZ +### `todo`/`deadline`/`event` - Add a task +Adds a task of the given type. +> **NOTE** +> +> For tasks with dates, the date can be given as: +> 1. `monday`, `tuesday`, ... which Changoose will understand as the next Monday, Tuesday etc. +> 2. `today` or `tomorrow`, which Changoose understands as 23:59 of the current day, or the next day. +> 3. For more flexibility, these are the date formats which Changoose understands: +> - `yyyy-MM-dd HHmm` e.g. 2023-08-10 1600 +> - `yyyyMMdd HHmm` e.g. 20230810 1600 +> - `d MMM yyyy`, e.g. 10 Aug 2023 +> - `d MMMM yyyy`. e.g. 10 Aug 2023 -Description of the feature. +Example of usage: -## Usage +`todo TASK NAME` + +`deadline TASK NAME /by DEADLINE_DATE` + +`event TASK NAME /from START_DATE /to END_DATE` + +``` +Got it. I've added this task: +... +Now you have x task(s) in the list. +``` + +### `list` - List all added tasks +Lists all added tasks with a task number prefixed to them. + +Example of usage: + +`list` + +``` +1. ... +2. ... +... +``` + +### `mark`/`unmark` - Mark a task as complete/incomplete +Marks a task as complete, or Unmark a task. + +> **NOTE** +> +> The task number of a task can be obtained by the `list` command -### `Keyword` - Describe action +Example of usage: -Describe the action and its outcome. +`mark NUMBER` -Example of usage: +`unmark NUMBER` + +``` +Nice! I've marked this task as done: + [T][X] some Todo task +``` +or +``` +OK, I've unmarked this task: + [T][] some Todo task +``` -`keyword (optional arguments)` +### `delete` - Delete a task +Deletes an added task. -Expected outcome: +> **NOTE** +> +> The task number of a task can be obtained by the `list` command + +Example of usage: -Description of the outcome. +`delete NUMBER` ``` -expected output +Noted. I have removed this task: + [T][X] some Todo task +Now you have x task in the list. +``` +### `find` - Search for a task +Finds all tasks with the given keyword + +> **NOTE** +> +> The search is case-insensitive: `lower_case` is treated the same as `UPPER_CASE` +> Changoose can search for incomplete keywords. `home` will return tasks with names `go home` or `do homework`. + +Example of usage: + +`find KEYWORD` + ``` +Found x matching tasks in your list! +1. ... +2. ... +... +``` \ No newline at end of file diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..aa6b2a5658 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/duke/DialogBox.java b/src/main/java/duke/DialogBox.java new file mode 100644 index 0000000000..1286339296 --- /dev/null +++ b/src/main/java/duke/DialogBox.java @@ -0,0 +1,61 @@ +package duke; + +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; + +/** + * 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); + } + + /** + * 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 getDukeDialog(String text, Image img) { + var db = new DialogBox(text, img); + db.flip(); + return db; + } +} diff --git a/src/main/java/duke/Duke.java b/src/main/java/duke/Duke.java new file mode 100644 index 0000000000..d294332c41 --- /dev/null +++ b/src/main/java/duke/Duke.java @@ -0,0 +1,143 @@ +package duke; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import duke.exception.DukeStorageException; +import duke.service.CliParserService; +import duke.service.CommandFactory; +import duke.service.OutputService; +import duke.service.StorageService; +import duke.service.TaskFactory; +import duke.service.UiService; +import duke.tasks.Task; +import duke.tasks.TaskList; + +/** + * Duke is responsible for task management, and exposes various methods to manipulate the Task List. + */ +public class Duke { + private final String botName; + private final TaskList taskList; + private final UiService uiService; + private final CliParserService cliParserService; + + /** + * No-args constructor for Duke. Sets up the various services. + */ + public Duke() { + this.botName = "Changoose"; + this.taskList = new TaskList(); + OutputService outputService = new OutputService(); + this.uiService = new UiService(outputService); + TaskFactory taskFactory = new TaskFactory(); + CommandFactory commandFactory = new CommandFactory(taskFactory, this, uiService); + this.cliParserService = new CliParserService(uiService, commandFactory); + } + + /** + * Initializes the StorageService and attempts to load the stored tasks into taskList. + * + * @return A string containing the greet message, and any additional info about the initialization of the + * StorageService. + */ + public String initStorage() { + try { + StorageService storageService = new StorageService(); + List displayText = new ArrayList<>(); + if (storageService.wasFileCorrupted()) { + displayText.add(uiService.storageFileCorruptedMessage()); + } + taskList.loadFromStorage(storageService); + displayText.add(uiService.greetMessage(getBotName())); + return uiService.formatGenericMessage(displayText); + } catch (DukeStorageException e) { + return uiService.formatStorageInitializationFailure(); + } + } + + /** + * Returns the result of parsing and executing the input. + * + * @param input The given input to be parsed and executed. + * @return A string representing the result of executing the parsed input. + */ + public String getResponse(String input) { + return cliParserService.parse(input); + } + + /** + * Returns the name of the Duke instance. + * + * @return the name of the Duke instance. + */ + public String getBotName() { + return botName; + } + + /** + * Adds a new task to the internal task list. + * + * @param task The task to be added. + * @throws DukeStorageException If an error occurs while saving to storage. + */ + public void addTask(Task task) throws DukeStorageException { + taskList.addTask(task); + } + + /** + * Deletes a task based on its index in the task list. + * + * @param index The index of the task to be deleted. + * @return An optional containing the deleted task, empty if the index was invalid. + * @throws DukeStorageException If an error occurs while updating storage. + */ + public Optional deleteTask(int index) throws DukeStorageException { + return taskList.deleteTask(index); + } + + /** + * Marks a task as completed based on its index. + * + * @param index The index of the task to be marked. + * @return An optional containing the marked task, empty if the index was invalid. + * @throws DukeStorageException If an error occurs while updating storage. + */ + public Optional markTask(int index) throws DukeStorageException { + return taskList.markTask(index); + } + + /** + * Unmarks a task, indicating it's not completed. + * + * @param index The index of the task to be unmarked. + * @return An optional containing the unmarked task, empty if the index was invalid. + * @throws DukeStorageException If an error occurs while updating storage. + */ + public Optional unmarkTask(int index) throws DukeStorageException { + return taskList.unmarkTask(index); + } + + public List searchTasks(String keyword) { + return taskList.searchTasks(keyword); + } + + /** + * Retrieves the list of tasks currently managed by Duke. + * + * @return A list of tasks. + */ + public List getTaskList() { + return taskList.getTaskList(); + } + + /** + * Returns the total number of tasks currently managed by Duke. + * + * @return Number of tasks. + */ + public int getNumberOfTasks() { + return taskList.getNumberOfTasks(); + } +} diff --git a/src/main/java/duke/Launcher.java b/src/main/java/duke/Launcher.java new file mode 100644 index 0000000000..e4ef6b4628 --- /dev/null +++ b/src/main/java/duke/Launcher.java @@ -0,0 +1,12 @@ +package duke; + +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/duke/Main.java b/src/main/java/duke/Main.java new file mode 100644 index 0000000000..a2a4e08ede --- /dev/null +++ b/src/main/java/duke/Main.java @@ -0,0 +1,49 @@ +package duke; + +import java.io.IOException; + +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Scene; +import javafx.scene.layout.VBox; +import javafx.stage.Stage; + +/** + * The Main class serves as the primary entry point for the Duke application. + * process for the application's Command-Line Interface (CLI). + */ +public class Main extends Application { + private Duke changooseBot; + + /** + * The main entry point for all JavaFX applications. + * The start method is called after the init method has returned, + * and after the system is ready for the application to begin running. + * + *

+ * NOTE: This method is called on the JavaFX Application Thread. + *

+ * + * @param stage the primary stage for this application, onto which + * the application scene can be set. + * Applications may create other stages, if needed, but they will not be + * primary stages. + */ + @Override + public void start(Stage stage) { + try { + FXMLLoader fxmlLoader = new FXMLLoader(Main.class.getResource("/view/MainWindow.fxml")); + VBox rootLayout = fxmlLoader.load(); + Scene scene = new Scene(rootLayout); + stage.setScene(scene); + MainWindow mainWindowController = fxmlLoader.getController(); + changooseBot = new Duke(); + mainWindowController.setDuke(changooseBot); + String startUpMessage = changooseBot.initStorage(); + mainWindowController.addMessageFromDuke(startUpMessage); + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/duke/MainWindow.java b/src/main/java/duke/MainWindow.java new file mode 100644 index 0000000000..117e2db8bb --- /dev/null +++ b/src/main/java/duke/MainWindow.java @@ -0,0 +1,63 @@ +package duke; + +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 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/DaUser.png")); + private Image dukeImage = new Image(this.getClass().getResourceAsStream("/images/DaDuke.png")); + + @FXML + public void initialize() { + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + } + + public void setDuke(Duke d) { + duke = d; + } + + /** + * Creates one dialog box that echoes a message from Duke, and then appends it to the dialog container. + * + * @param message The message to be displayed by Duke. + */ + public void addMessageFromDuke(String message) { + dialogContainer.getChildren().add( + DialogBox.getDukeDialog(message, dukeImage) + ); + } + + /** + * 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(); + } +} diff --git a/src/main/java/duke/commands/AddTaskCommand.java b/src/main/java/duke/commands/AddTaskCommand.java new file mode 100644 index 0000000000..7b62cd833b --- /dev/null +++ b/src/main/java/duke/commands/AddTaskCommand.java @@ -0,0 +1,56 @@ +package duke.commands; + +import java.util.List; + +import duke.Duke; +import duke.exception.DukeStorageException; +import duke.exception.TaskParseException; +import duke.exception.TimeUtilException; +import duke.service.TaskFactory; +import duke.service.UiService; +import duke.tasks.Task; + +/** + * Represents a command to add a task in the Duke application. + */ +public class AddTaskCommand extends Command { + private final String taskType; + private final List argsList; + private final TaskFactory taskFactory; + + /** + * Constructs an AddTaskCommand. + * + * @param dukeBot The main Duke instance. + * @param uiService The UI service for interactions. + * @param taskType The type of the task to be added. + * @param argsList The arguments required to create the task. + * @param taskFactory The factory to create tasks. + */ + public AddTaskCommand(Duke dukeBot, UiService uiService, + String taskType, List argsList, TaskFactory taskFactory) { + super(dukeBot, uiService); + this.taskType = taskType; + this.argsList = argsList; + this.taskFactory = taskFactory; + } + + /** + * Executes the command to add a task. + * + * @return A string representing the status of the task addition. + * It either confirms the task addition or details any errors encountered. + */ + @Override + public String execute() { + try { + Task task = taskFactory.createTask(taskType, argsList); + dukeBot.addTask(task); + return uiService.formatAddTask(task, dukeBot.getNumberOfTasks()); + } catch (TaskParseException | TimeUtilException e) { + return uiService.formatGenericMessage(e.getMessage()); + } catch (DukeStorageException e) { + return uiService.formatStorageAddFailure(); + } + } +} diff --git a/src/main/java/duke/commands/Command.java b/src/main/java/duke/commands/Command.java new file mode 100644 index 0000000000..269fc5b099 --- /dev/null +++ b/src/main/java/duke/commands/Command.java @@ -0,0 +1,42 @@ +package duke.commands; + +import duke.Duke; +import duke.service.UiService; + +/** + * Represents an abstract command that can be executed in the Duke application. + *

+ * All commands that are intended to be executed in Duke should extend this class. + *

+ */ +public abstract class Command { + protected Duke dukeBot; + protected UiService uiService; + + /** + * Constructs a Command with the given Duke instance and UI service. + * + * @param dukeBot The main Duke instance. + * @param uiService The UI service for interactions. + */ + protected Command(Duke dukeBot, UiService uiService) { + this.dukeBot = dukeBot; + this.uiService = uiService; + } + + /** + * Executes the command. + * + * @return a String describing the output of the Command. + */ + public abstract String execute(); + + /** + * Indicates if the command should cause the program to exit. + * + * @return False by default; should be overridden by commands that cause program exit. + */ + public boolean isExit() { + return false; + } +} diff --git a/src/main/java/duke/commands/DeleteTaskCommand.java b/src/main/java/duke/commands/DeleteTaskCommand.java new file mode 100644 index 0000000000..b6d3fe237a --- /dev/null +++ b/src/main/java/duke/commands/DeleteTaskCommand.java @@ -0,0 +1,44 @@ +package duke.commands; + +import java.util.Optional; + +import duke.Duke; +import duke.exception.DukeStorageException; +import duke.service.UiService; +import duke.tasks.Task; + +/** + * Represents a command to delete a task from the Duke application. + */ +public class DeleteTaskCommand extends Command { + private final int taskId; + + /** + * Constructs a DeleteTaskCommand. + * + * @param dukeBot The main Duke instance. + * @param uiService The UI service for interactions. + * @param taskId The ID of the task to be deleted. + */ + public DeleteTaskCommand(Duke dukeBot, UiService uiService, int taskId) { + super(dukeBot, uiService); + this.taskId = taskId; + } + + /** + * Executes the command to delete a task. + * + * @return A string representing the status of the task deletion. + * It either confirms the task deletion or details any errors encountered. + */ + @Override + public String execute() { + try { + Optional optionalTask = dukeBot.deleteTask(taskId - 1); + return optionalTask.map(task -> uiService.formatDeleteTask(task, dukeBot.getNumberOfTasks())) + .orElseGet(() -> uiService.formatInvalidTaskIndexProvided(taskId, dukeBot.getNumberOfTasks())); + } catch (DukeStorageException e) { + return uiService.formatStorageDeleteFailure(); + } + } +} diff --git a/src/main/java/duke/commands/ExitCommand.java b/src/main/java/duke/commands/ExitCommand.java new file mode 100644 index 0000000000..3a1d360385 --- /dev/null +++ b/src/main/java/duke/commands/ExitCommand.java @@ -0,0 +1,42 @@ +package duke.commands; + +import duke.Duke; +import duke.service.UiService; + +/** + * Represents a command to exit the Duke application. + */ +public class ExitCommand extends Command { + + /** + * Constructs an ExitCommand. + * + * @param dukeBot The main Duke instance. + * @param uiService The UI service for interactions. + */ + public ExitCommand(Duke dukeBot, UiService uiService) { + super(dukeBot, uiService); + } + + /** + * Executes the command to exit Duke, although the actual exit mechanism + * is handled outside this class. + * + * @return A String literal "EXIT". + */ + @Override + public String execute() { + // will be handled outside of this class. + return "EXIT"; + } + + /** + * Indicates that this command causes the program to exit. + * + * @return True. + */ + @Override + public boolean isExit() { + return true; + } +} diff --git a/src/main/java/duke/commands/FindTaskCommand.java b/src/main/java/duke/commands/FindTaskCommand.java new file mode 100644 index 0000000000..6846749d82 --- /dev/null +++ b/src/main/java/duke/commands/FindTaskCommand.java @@ -0,0 +1,38 @@ +package duke.commands; + +import java.util.List; + +import duke.Duke; +import duke.service.UiService; +import duke.tasks.Task; + +/** + * Represents a Command to find tasks based on the provided keyword. + */ +public class FindTaskCommand extends Command { + private final String keyword; + + /** + * Constructs a FindTaskCommand + * + * @param dukeBot The Duke instance. + * @param uiService The UI service for interactions. + * @param keyword The keyword to look for in the taskList. + */ + public FindTaskCommand(Duke dukeBot, UiService uiService, String keyword) { + super(dukeBot, uiService); + this.keyword = keyword; + } + + /** + * Executes the command to find tasks based on the provided keyword. + * + * @return A string representing the tasks that matched the keyword. If no tasks matched, + * it returns a string indicating that no tasks were found. + */ + @Override + public String execute() { + List matchedTasks = dukeBot.searchTasks(keyword.trim()); + return uiService.formatFoundTasks(matchedTasks, keyword); + } +} diff --git a/src/main/java/duke/commands/ListCommand.java b/src/main/java/duke/commands/ListCommand.java new file mode 100644 index 0000000000..ed86cf0bb5 --- /dev/null +++ b/src/main/java/duke/commands/ListCommand.java @@ -0,0 +1,32 @@ +package duke.commands; + +import duke.Duke; +import duke.service.UiService; + +/** + * Represents a command to list all tasks in the Duke application. + */ +public class ListCommand extends Command { + + /** + * Constructs a ListCommand. + * + * @param dukeBot The main Duke instance. + * @param uiService The UI service for interactions. + */ + public ListCommand(Duke dukeBot, UiService uiService) { + super(dukeBot, uiService); + } + + /** + * Executes the command to display the list of tasks. + * + * @return A string representing the tasks in the task list, prefixed by their index. + * If there are no tasks, it returns a string indicating that there are no + * tasks in the task list. + */ + @Override + public String execute() { + return uiService.formatTaskList(dukeBot.getTaskList()); + } +} diff --git a/src/main/java/duke/commands/MarkTaskCommand.java b/src/main/java/duke/commands/MarkTaskCommand.java new file mode 100644 index 0000000000..0b63fd9d9a --- /dev/null +++ b/src/main/java/duke/commands/MarkTaskCommand.java @@ -0,0 +1,43 @@ +package duke.commands; + +import java.util.Optional; + +import duke.Duke; +import duke.exception.DukeStorageException; +import duke.service.UiService; +import duke.tasks.Task; + +/** + * Represents a command to mark a task as completed in the Duke application. + */ +public class MarkTaskCommand extends Command { + private final int taskId; + + /** + * Constructs a MarkTaskCommand. + * + * @param dukeBot The main Duke instance. + * @param uiService The UI service for interactions. + * @param taskId The ID of the task to be marked. + */ + public MarkTaskCommand(Duke dukeBot, UiService uiService, int taskId) { + super(dukeBot, uiService); + this.taskId = taskId; + } + + /** + * Executes the command to mark a task as completed. + * + * @return A string representing the task that was marked as complete. + */ + @Override + public String execute() { + try { + Optional optionalTask = dukeBot.markTask(taskId - 1); + return optionalTask.map(task -> uiService.formatMarkTask(task)) + .orElseGet(() -> uiService.formatInvalidTaskIndexProvided(taskId, dukeBot.getNumberOfTasks())); + } catch (DukeStorageException e) { + return uiService.formatStorageMarkFailure(); + } + } +} diff --git a/src/main/java/duke/commands/UnmarkTaskCommand.java b/src/main/java/duke/commands/UnmarkTaskCommand.java new file mode 100644 index 0000000000..3d9f62aacf --- /dev/null +++ b/src/main/java/duke/commands/UnmarkTaskCommand.java @@ -0,0 +1,43 @@ +package duke.commands; + +import java.util.Optional; + +import duke.Duke; +import duke.exception.DukeStorageException; +import duke.service.UiService; +import duke.tasks.Task; + +/** + * Represents a command to unmark a task as completed in the Duke application. + */ +public class UnmarkTaskCommand extends Command { + private final int taskId; + + /** + * Constructs an UnmarkTaskCommand. + * + * @param dukeBot The main Duke instance. + * @param uiService The UI service for interactions. + * @param taskId The ID of the task to be unmarked. + */ + public UnmarkTaskCommand(Duke dukeBot, UiService uiService, int taskId) { + super(dukeBot, uiService); + this.taskId = taskId; + } + + /** + * Executes the command to unmark a task as completed. + * + * @return A string that represents the task that was unmarked. + */ + @Override + public String execute() { + try { + Optional optionalTask = dukeBot.unmarkTask(taskId - 1); + return optionalTask.map(task -> uiService.formatUnmarkTask(task)) + .orElseGet(() -> uiService.formatInvalidTaskIndexProvided(taskId, dukeBot.getNumberOfTasks())); + } catch (DukeStorageException e) { + return uiService.formatStorageUnmarkFailure(); + } + } +} diff --git a/src/main/java/duke/exception/DukeException.java b/src/main/java/duke/exception/DukeException.java new file mode 100644 index 0000000000..1d7a8cab1c --- /dev/null +++ b/src/main/java/duke/exception/DukeException.java @@ -0,0 +1,10 @@ +package duke.exception; + +/** + * Represents the general exception related to Duke operations. + */ +public class DukeException extends Exception { + public DukeException(String message) { + super(message); + } +} diff --git a/src/main/java/duke/exception/DukeStorageException.java b/src/main/java/duke/exception/DukeStorageException.java new file mode 100644 index 0000000000..0b0be9e87f --- /dev/null +++ b/src/main/java/duke/exception/DukeStorageException.java @@ -0,0 +1,10 @@ +package duke.exception; + +/** + * Represents an exception thrown when there's a storage related issue in Duke. + */ +public class DukeStorageException extends DukeException { + public DukeStorageException(String message) { + super(message); + } +} diff --git a/src/main/java/duke/exception/FileCorruptedException.java b/src/main/java/duke/exception/FileCorruptedException.java new file mode 100644 index 0000000000..cef717008a --- /dev/null +++ b/src/main/java/duke/exception/FileCorruptedException.java @@ -0,0 +1,10 @@ +package duke.exception; + +/** + * Represents an exception thrown when a file is found to be corrupted in Duke. + */ +public class FileCorruptedException extends DukeException { + public FileCorruptedException(String message) { + super(message); + } +} diff --git a/src/main/java/duke/exception/InvalidCommandInputException.java b/src/main/java/duke/exception/InvalidCommandInputException.java new file mode 100644 index 0000000000..b943568257 --- /dev/null +++ b/src/main/java/duke/exception/InvalidCommandInputException.java @@ -0,0 +1,10 @@ +package duke.exception; + +/** + * Represents an exception thrown when there's an invalid command input in Duke. + */ +public class InvalidCommandInputException extends DukeException { + public InvalidCommandInputException(String message) { + super(message); + } +} diff --git a/src/main/java/duke/exception/TaskParseException.java b/src/main/java/duke/exception/TaskParseException.java new file mode 100644 index 0000000000..67f850e678 --- /dev/null +++ b/src/main/java/duke/exception/TaskParseException.java @@ -0,0 +1,10 @@ +package duke.exception; + +/** + * Represents an exception thrown when there's an error in parsing a task in Duke. + */ +public class TaskParseException extends DukeException { + public TaskParseException(String message) { + super(message); + } +} diff --git a/src/main/java/duke/exception/TimeUtilException.java b/src/main/java/duke/exception/TimeUtilException.java new file mode 100644 index 0000000000..243efb425d --- /dev/null +++ b/src/main/java/duke/exception/TimeUtilException.java @@ -0,0 +1,10 @@ +package duke.exception; + +/** + * Represents an exception thrown when there's an error related to time utility functions in Duke. + */ +public class TimeUtilException extends DukeException { + public TimeUtilException(String message) { + super(String.format("%s %s", "[TimeUtil]", message)); + } +} diff --git a/src/main/java/duke/exception/UnknownCommandException.java b/src/main/java/duke/exception/UnknownCommandException.java new file mode 100644 index 0000000000..e4c7d028ca --- /dev/null +++ b/src/main/java/duke/exception/UnknownCommandException.java @@ -0,0 +1,10 @@ +package duke.exception; + +/** + * Represents an exception thrown when an unknown command is encountered in Duke. + */ +public class UnknownCommandException extends DukeException { + public UnknownCommandException(String message) { + super(message); + } +} diff --git a/src/main/java/duke/service/CliParserService.java b/src/main/java/duke/service/CliParserService.java new file mode 100644 index 0000000000..0b6e91989c --- /dev/null +++ b/src/main/java/duke/service/CliParserService.java @@ -0,0 +1,122 @@ +package duke.service; + +import java.util.ArrayList; +import java.util.List; + +import duke.commands.Command; +import duke.exception.InvalidCommandInputException; +import duke.exception.UnknownCommandException; + +/** + * Provides functionality to parse and execute commands from the command line interface. + *

+ * This service is responsible for continuously reading commands from the CLI, parsing them into + * their respective components, and then executing the associated commands using a {@link CommandFactory}. + *

+ */ +public class CliParserService { + private final UiService uiService; + private final CommandFactory commandFactory; + + /** + * Constructs a new instance of the CLI parser service. + * + * @param uiService The UI service to use for interactions with the user. + * @param commandFactory The command factory to use for creating command objects. + */ + public CliParserService(UiService uiService, CommandFactory commandFactory) { + this.uiService = uiService; + this.commandFactory = commandFactory; + } + + /** + * Reads and executes commands from the command line interface continuously. + *

+ * This method will parse the given input into command components, create the associated {@link Command} objects + * using the {@link CommandFactory}, and then execute the commands. + *

+ * + * @param input The input to be parsed. + * @return The String returned from executing the commands. + */ + public String parse(String input) { + ParseResult parseResult = parseCommandAndArguments(input); + String commandType = parseResult.getCommandType(); + List arguments = parseResult.getArguments(); + try { + Command command = commandFactory.createCommand(commandType, arguments); + if (command.isExit()) { + return uiService.formatBye(); + } + return command.execute(); + } catch (UnknownCommandException | InvalidCommandInputException e) { + return uiService.formatGenericMessage(e.getMessage()); + } + } + + /** + * Parses a command line into its main command and associated arguments. + * + * @param line The command line to parse. + * @return A {@link ParseResult} object containing the parsed command and its arguments. + */ + public ParseResult parseCommandAndArguments(String line) { + String trimmedLine = line.trim(); + List arguments = new ArrayList<>(); + + // Split the command and its primary argument + String[] splitBySpace = trimmedLine.split(" ", 2); + String commandType = splitBySpace[0].toLowerCase(); + + // If there's more than just the command, handle the arguments + if (splitBySpace.length > 1) { + // primaryArg refers to either task name, or the task index. + String primaryArg = splitBySpace[1].split("/")[0].trim(); + arguments.add(primaryArg); + + // Split the rest by slashes + String[] splitBySlash = splitBySpace[1].split("/"); + for (int i = 1; i < splitBySlash.length; ++i) { // Start at 1 to skip the task name + arguments.add(splitBySlash[i].trim()); + } + } + return new ParseResult(commandType, arguments); + } + + /** + * Represents the result of parsing a command line into its main command and arguments. + */ + public static final class ParseResult { + private final String commandType; + private final List arguments; + + /** + * Constructs a new parse result. + * + * @param commandType The parsed command type. + * @param arguments The list of parsed arguments. + */ + ParseResult(String commandType, List arguments) { + this.commandType = commandType; + this.arguments = arguments; + } + + /** + * Retrieves the parsed command type. + * + * @return The command type as a string. + */ + public String getCommandType() { + return commandType; + } + + /** + * Retrieves the list of parsed arguments. + * + * @return A list of arguments. + */ + public List getArguments() { + return arguments; + } + } +} diff --git a/src/main/java/duke/service/CommandFactory.java b/src/main/java/duke/service/CommandFactory.java new file mode 100644 index 0000000000..be54791368 --- /dev/null +++ b/src/main/java/duke/service/CommandFactory.java @@ -0,0 +1,110 @@ +package duke.service; + +import java.util.List; + +import duke.Duke; +import duke.commands.AddTaskCommand; +import duke.commands.Command; +import duke.commands.DeleteTaskCommand; +import duke.commands.ExitCommand; +import duke.commands.FindTaskCommand; +import duke.commands.ListCommand; +import duke.commands.MarkTaskCommand; +import duke.commands.UnmarkTaskCommand; +import duke.exception.InvalidCommandInputException; +import duke.exception.UnknownCommandException; + +/** + * A factory class responsible for producing commands based on user inputs. + *

+ * This class interprets the user's command and its associated arguments + * to generate the correct {@link Command} object that corresponds to the user's request. + *

+ */ +public class CommandFactory { + private TaskFactory taskFactory; + private Duke dukeBot; + private UiService uiService; + + /** + * Initializes a new instance of CommandFactory. + * + * @param taskFactory The factory responsible for creating tasks. + * @param dukeBot The main Duke bot instance. + * @param uiService The UI service instance for user interactions. + */ + public CommandFactory(TaskFactory taskFactory, Duke dukeBot, UiService uiService) { + this.taskFactory = taskFactory; + this.dukeBot = dukeBot; + this.uiService = uiService; + } + + /** + * Creates a {@link Command} object based on the provided command and its arguments. + * + * @param command The main user command as a string. + * @param args A list of arguments associated with the command. + * @return The corresponding {@link Command} object. + * @throws UnknownCommandException If the provided command string does not match any known command. + * @throws InvalidCommandInputException If the command input is invalid or incomplete. + */ + public Command createCommand(String command, List args) + throws UnknownCommandException, InvalidCommandInputException { + switch (command) { + case "bye": + return new ExitCommand(dukeBot, uiService); + case "list": + return new ListCommand(dukeBot, uiService); + case "mark": + checkValidTaskNumberArgument(args); + int markId = Integer.parseInt(args.get(0)); + return new MarkTaskCommand(dukeBot, uiService, markId); + case "unmark": + checkValidTaskNumberArgument(args); + int unmarkId = Integer.parseInt(args.get(0)); + return new UnmarkTaskCommand(dukeBot, uiService, unmarkId); + case "delete": + checkValidTaskNumberArgument(args); + int deleteId = Integer.parseInt(args.get(0)); + return new DeleteTaskCommand(dukeBot, uiService, deleteId); + case "find": + if (args.isEmpty()) { + throw new InvalidCommandInputException("Provide a keyword for find command! :<"); + } + return new FindTaskCommand(dukeBot, uiService, args.get(0)); + case "todo": + case "deadline": + case "event": + return new AddTaskCommand(dukeBot, uiService, command, args, taskFactory); + default: + throw new UnknownCommandException(String.format("Command: %s not recognized! :<", command)); + } + } + + /** + * Checks if the provided string is numeric. + * + * @param str The string to check. + * @return {@code true} if the string is numeric, otherwise {@code false}. + */ + private boolean isNumeric(String str) { + try { + Integer.parseInt(str); + return true; + } catch (NumberFormatException e) { + return false; + } + } + + /** + * Validates that the given arguments list contains a numeric value as its first item. + * + * @param argsList The list of arguments. + * @throws InvalidCommandInputException If the list is empty or the first item is not numeric. + */ + private void checkValidTaskNumberArgument(List argsList) throws InvalidCommandInputException { + if (argsList.isEmpty() || !isNumeric(argsList.get(0))) { + throw new InvalidCommandInputException("A numeric argument should be provided."); + } + } +} diff --git a/src/main/java/duke/service/OutputService.java b/src/main/java/duke/service/OutputService.java new file mode 100644 index 0000000000..6770fa756a --- /dev/null +++ b/src/main/java/duke/service/OutputService.java @@ -0,0 +1,85 @@ +package duke.service; + +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import duke.tasks.Task; + +/** + * Handles the display of information to the user with standardized formatting. + *

+ * The OutputService ensures consistent display formats, particularly with the use + * of indentation and dividers for enhanced readability. + *

+ */ +public class OutputService { + private static final int indentLength = 4; + private final String divider = appendNewLine( + indentLeft(String.format("%40s", "").replace(" ", "-"))); + + /** + * Echos the provided input string to the user without a prefix. + * + * @param input The string to be displayed. + */ + public String echo(String input) { + return echo(input, ""); + } + + /** + * Echos the provided input string to the user with the specified prefix. + * + * @param input The string to be displayed. + * @param prefix A prefix to be added before the input string. + */ + public String echo(String input, String prefix) { + return echo(List.of(prefix + input)); + } + + /** + * Echos a list of strings to the user with standardized formatting. + * + * @param inputs The list of strings to be displayed. + */ + public String echo(List inputs) { + StringBuilder sb = new StringBuilder(); + sb.append(divider); + inputs.stream().map(this::indentLeft) + .map(this::appendNewLine) + .forEach(sb::append); + sb.append(divider); + return sb.toString(); + } + + /** + * Adds a standardized indentation to the beginning of each line of the given string. + * + * @param input The string that requires indentation. + * @return The input string with the standardized indentation applied. + */ + public String indentLeft(String input) { + String indent = String.format("%" + indentLength + "s", ""); + String[] lines = input.split(System.lineSeparator()); // handle Unix and Windows new lines. + for (int i = 0; i < lines.length; i++) { + lines[i] = indent + lines[i]; + } + return String.join(System.lineSeparator(), lines); + } + + /** + * Appends to the front of each task in a list of tasks to the user with task numbers. + * + * @param taskList The list of tasks to be formatted. + */ + public List formatTaskList(List taskList) { + return Stream.iterate(0, i -> i + 1) + .limit(taskList.size()) + .map(i -> String.format("%s. %s", i + 1, taskList.get(i))) // taskList is 0-indexed. display is 1-indexed. + .collect(Collectors.toList()); + } + + private String appendNewLine(String line) { + return String.format("%s%n", line); + } +} diff --git a/src/main/java/duke/service/StorageService.java b/src/main/java/duke/service/StorageService.java new file mode 100644 index 0000000000..d1af709a8a --- /dev/null +++ b/src/main/java/duke/service/StorageService.java @@ -0,0 +1,158 @@ +package duke.service; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; + +import duke.exception.DukeStorageException; +import duke.exception.FileCorruptedException; +import duke.tasks.Task; + +/** + * Manages the storage and retrieval of {@link Task} objects from a local file. + *

+ * This service class provides an abstraction for the storage operations. It manages the tasks + * in the local storage and offers functionalities such as loading, saving, and deleting tasks. + *

+ */ +public class StorageService { + public static final String PATH_NAME = "./data"; + public static final String FILE_NAME = "./data/duke.txt"; + private final File directory; + private final File tasksStorageFile; + private boolean wasFileCorrupted; + + /** + * Initializes a new StorageService, ensuring the existence of the storage directory and file. + * + * @throws DukeStorageException If there's any issue creating or accessing the storage. + */ + public StorageService() throws DukeStorageException { + this.directory = new File(PATH_NAME); + this.tasksStorageFile = new File(FILE_NAME); + this.wasFileCorrupted = false; + initDirectory(); + initFile(); + } + + /** + * Checks if the storage file was corrupted during the last operation. + * + * @return {@code true} if the file was corrupted, otherwise {@code false}. + */ + public boolean wasFileCorrupted() { + return wasFileCorrupted; + } + + /** + * Loads tasks from the storage file. + * + * @return A list of {@link Task} objects loaded from the storage file. + */ + public List loadTasks() { + try { + return getTasks(tasksStorageFile); + } catch (FileCorruptedException e) { + wasFileCorrupted = true; + return new ArrayList<>(); // return an empty list if file is corrupted + } + } + + /** + * Saves a single task to the storage. + * + * @param task The task to be saved. + * @throws DukeStorageException If there's an error during the save operation. + */ + public void saveTask(Task task) throws DukeStorageException { + List tasks = loadTasks(); + tasks.add(task); + writeTasksToFile(tasks); + } + + /** + * Saves a list of tasks to the storage. + * + * @param taskList The list of tasks to be saved. + * @throws DukeStorageException If there's an error during the save operation. + */ + public void saveTasks(List taskList) throws DukeStorageException { + writeTasksToFile(taskList); + } + + /** + * Deletes a task from the storage based on its index. + * + * @param index The index of the task in the storage list. + * @throws DukeStorageException If there's an error during the deletion operation. + */ + public void deleteTask(int index) throws DukeStorageException { + List tasks = loadTasks(); + if (index >= 0 && index < tasks.size()) { + tasks.remove(index); + writeTasksToFile(tasks); + } + } + + /** + * Deletes a specified task from the storage. + * + * @param task The task to be deleted. + * @throws DukeStorageException If there's an error during the deletion operation. + */ + public void deleteTask(Task task) throws DukeStorageException { + List tasks = loadTasks(); + tasks.remove(task); + writeTasksToFile(tasks); + } + + // Helper methods below + private void writeTasksToFile(List tasks) throws DukeStorageException { + try { + FileOutputStream fos = new FileOutputStream(FILE_NAME); + ObjectOutputStream oos = new ObjectOutputStream(fos); + oos.writeObject(tasks); + } catch (IOException e) { + throw new DukeStorageException(String.format("Failed to write tasks to file!%nError: %s", e.getMessage())); + } + } + + private List getTasks(File file) throws FileCorruptedException { + if (!file.exists() || file.length() == 0) { + return new ArrayList<>(); + } + + try (FileInputStream fis = new FileInputStream(file); + ObjectInputStream ois = new ObjectInputStream(fis)) { + @SuppressWarnings("unchecked") + List storedTaskList = (List) ois.readObject(); + return storedTaskList; + } catch (IOException | ClassNotFoundException e) { + throw new FileCorruptedException(String.format("Failed to load tasks!%nError: %s", e.getMessage())); + } + } + + private void initDirectory() throws DukeStorageException { + try { + Files.createDirectories(directory.toPath()); + } catch (IOException e) { + throw new DukeStorageException(String.format("Failed to create/load directory at %s", PATH_NAME)); + } + } + + private void initFile() throws DukeStorageException { + if (!tasksStorageFile.exists()) { + try { + Files.createFile(tasksStorageFile.toPath()); + } catch (IOException e) { + throw new DukeStorageException(String.format("Failed to create/load %s file", FILE_NAME)); + } + } + } +} diff --git a/src/main/java/duke/service/TaskFactory.java b/src/main/java/duke/service/TaskFactory.java new file mode 100644 index 0000000000..cf0ccef22f --- /dev/null +++ b/src/main/java/duke/service/TaskFactory.java @@ -0,0 +1,100 @@ +package duke.service; + +import java.time.LocalDateTime; +import java.util.List; + +import duke.exception.TaskParseException; +import duke.exception.TimeUtilException; +import duke.tasks.DeadlineTask; +import duke.tasks.EventTask; +import duke.tasks.Task; +import duke.tasks.TaskType; +import duke.tasks.TodoTask; +import duke.util.TimeUtil; + +/** + * Factory class responsible for creating Task objects based on their type and given arguments. + *

+ * This class provides an abstraction over the task creation process. It receives a task type and + * a list of arguments, then produces the corresponding task instance. + *

+ */ +public class TaskFactory { + + /** + * Creates a task instance based on the provided task type and arguments. + * + * @param taskType The type of task to be created. It should match one of the enum values in {@code TaskType}. + * @param argsList The list of arguments required for the task. The first item is always the task name. + * Further items depend on the task type (e.g., due date for deadlines, start and + * end times for events). + * @return The created Task object. + * @throws TaskParseException If there's an error in the task's format or arguments. + * @throws TimeUtilException If there's an error in parsing the date and time. + */ + public Task createTask(String taskType, List argsList) + throws TaskParseException, TimeUtilException { + + if (argsList.isEmpty()) { + throw new TaskParseException("usage: TaskType(todo | deadline | event) " + + "TaskName " + + "[/StartDate] [/EndDate]"); + } + + String taskName = argsList.remove(0); + + // Convert the provided taskType string to the TaskType enum. + TaskType typeEnum; + try { + typeEnum = TaskType.valueOf(taskType.toUpperCase()); + } catch (IllegalArgumentException e) { + throw new TaskParseException("Invalid task type: " + taskType); + } + + switch (typeEnum) { + case TODO: + if (!argsList.isEmpty()) { + throw new TaskParseException("Error: Todo tasks should not have arguments"); + } + return new TodoTask(taskName); + + case DEADLINE: + if (argsList.size() != 1) { + throw new TaskParseException("Usage: deadline taskName /by 10 May 2023"); + } + // Ensuring the deadline time is prefixed with "by ". + if (!argsList.get(0).startsWith("by ")) { + throw new TaskParseException("Error: Deadline tasks must have an end date prefixed with '/by'.\n"); + } + // Parsing the end date without the "by " prefix. + LocalDateTime endDeadlineDate = TimeUtil.parseDateTimeString( + argsList.get(0).substring(3).trim() + ); + return new DeadlineTask(taskName, endDeadlineDate); + + case EVENT: + if (argsList.size() != 2) { + throw new TaskParseException("Usage: event taskName /from 10 May 2023 /to 20 May 2023"); + } + // Ensuring the start and end dates are prefixed correctly for event tasks. + if (!argsList.get(0).startsWith("from ") || !argsList.get(1).startsWith("to ")) { + throw new TaskParseException("Error: Event tasks must have a start date prefixed with '/from' " + + "and an end date prefixed with '/to'.\n"); + } + // Parsing the start date without the "from " prefix and the end date without the "to " prefix. + LocalDateTime startEventDate = TimeUtil.parseDateTimeString( + argsList.get(0).substring(5).trim() + ); + LocalDateTime endEventDate = TimeUtil.parseDateTimeString( + argsList.get(1).substring(3).trim() + ); + if (startEventDate.isAfter(endEventDate)) { + throw new TaskParseException("Error: Start date of the event cannot be after the end date"); + } + return new EventTask(taskName, startEventDate, endEventDate); + + default: + throw new TaskParseException("Unhandled task type: " + taskType); + } + } +} diff --git a/src/main/java/duke/service/UiService.java b/src/main/java/duke/service/UiService.java new file mode 100644 index 0000000000..1fbb0f4290 --- /dev/null +++ b/src/main/java/duke/service/UiService.java @@ -0,0 +1,226 @@ +package duke.service; + +import java.util.ArrayList; +import java.util.List; + +import duke.tasks.Task; + +/** + * Provides a set of methods for displaying user interface messages and task information. + *

+ * This service acts as an intermediate between the logic and the actual output service. It simplifies + * the process of generating structured messages for different operations within the application. + *

+ */ +public class UiService { + private final OutputService outputService; + + /** + * Creates a new UiService instance with a specified OutputService. + * + * @param outputService The service to handle actual output operations. + */ + public UiService(OutputService outputService) { + this.outputService = outputService; + } + + /** + * Displays a greeting message with the given bot's name. + * + * @param botName Name of the bot. + * @return A String containing the greeting message. + */ + public String greetMessage(String botName) { + return String.format("Hello! I'm %s%nWhat can I do for you?", botName); + } + + /** + * Displays a farewell message. + * + * @return A string containing the farewell message. + */ + public String formatBye() { + return outputService.echo("Bye! Hope to see you again soon!"); + } + + /** + * Displays a generic message to the user. + * + * @param message The message to be displayed. + * @return The message to be displayed, formatted by OutputService. + */ + public String formatGenericMessage(String message) { + return outputService.echo(message); + } + + /** + * Displays a generic message to the user. + * + * @param messages The List of messages to be displayed. + * @return The messages to be displayed, formatted by OutputService. + */ + public String formatGenericMessage(List messages) { + return outputService.echo(messages); + } + + /** + * Warns the user that the task storage file has been corrupted. + * + * @return A string containing the warning message about the corrupted task storage file. + */ + public String storageFileCorruptedMessage() { + return "Warning: The existing tasks file was corrupted and has been reset."; + } + + /** + * Warns the user about a failure in initializing the storage. + * + * @return A string containing the warning message about the failed storage initialization. + */ + public String formatStorageInitializationFailure() { + return outputService.echo("Warning: Error initializing storage. " + + "Any changes made during this session will not be saved!"); + } + + /** + * Warns the user about a failure in adding a task to the storage. + * + * @return A string containing the warning message about the failed addition of the task to storage. + */ + public String formatStorageAddFailure() { + return outputService.echo("Failed to add task to storage! :<"); + } + + /** + * Warns the user about a failure in deleting a task from the storage. + * + * @return A string containing the warning message about the failed deletion of the task from storage. + */ + public String formatStorageDeleteFailure() { + return outputService.echo("Failed to delete task from storage! :<"); + } + + /** + * Warns the user about a failure in marking a task and saving changes to the storage. + * + * @return A string containing the warning message about the failed saving of the marked task to storage. + */ + public String formatStorageMarkFailure() { + return outputService.echo("Failed to save marked task to storage! :<"); + } + + /** + * Warns the user about a failure in un-marking a task and saving changes to the storage. + * + * @return A string containing the warning message about the failed saving of the unmarked task to storage. + */ + public String formatStorageUnmarkFailure() { + return outputService.echo("Failed to save unmarked task to storage! :<"); + } + + /** + * Prints the tasks in the taskList, prefixed by their index. + * + * @param taskList the taskList containing the tasks to be formatted. + * @return A string representation of the task list. + */ + public String formatTaskList(List taskList) { + return outputService.echo(outputService.formatTaskList(taskList)); + } + + /** + * Notifies the user when a task is successfully added to the taskList. + * + * @param task the task that was added. + * @param taskListSize the current size of the taskList + * @return A string indicating the status of the task list after adding a task. + */ + public String formatAddTask(Task task, int taskListSize) { + List displayText = new ArrayList<>(); + displayText.add("Got it. I've added this task:"); + displayText.add(outputService.indentLeft(task.toString())); + displayText.add(String.format("Now you have %s %s in the list.", + taskListSize, + taskListSize == 1 ? "task" : "tasks")); + return outputService.echo(displayText); + } + + /** + * Notifies the user when a task is successfully deleted from the taskList. + * + * @param task the task that was deleted. + * @param taskListSize the current size of the taskList + * @return A string indicating the status of the task list after deleting a task. + */ + public String formatDeleteTask(Task task, int taskListSize) { + List displayText = new ArrayList<>(); + displayText.add("Noted. I have removed this task:"); + displayText.add(outputService.indentLeft(task.toString())); + displayText.add(String.format("Now you have %s %s in the list.", + taskListSize, + taskListSize == 1 ? "task" : "tasks")); + return outputService.echo(displayText); + } + + /** + * Notifies the user when a task is successfully marked in the taskList. + * + * @param task the task that was marked. + * @return A string indicating the status of the task after marking it. + */ + public String formatMarkTask(Task task) { + List displayText = new ArrayList<>(); + displayText.add("Nice! I've marked this task as done:"); + displayText.add(outputService.indentLeft(task.toString())); + return outputService.echo(displayText); + } + + /** + * Notifies the user when a task is successfully unmarked from the taskList. + * + * @param task the task that was unmarked. + * @return A string indicating the status of the task after unmarking it. + */ + public String formatUnmarkTask(Task task) { + List displayText = new ArrayList<>(); + displayText.add("OK, I've unmarked this task:"); + displayText.add(outputService.indentLeft(task.toString())); + return outputService.echo(displayText); + } + + /** + * Notifies the user about an invalid task index provided. + * + * @param taskId The invalid task ID. + * @param taskListSize The current size of the task list. + * @return A string message indicating the invalidity of the task index. + */ + public String formatInvalidTaskIndexProvided(int taskId, int taskListSize) { + if (taskListSize == 0) { + return outputService.echo("There are no tasks left!"); + } + return outputService.echo(String.format("Invalid Task index: %s provided.%n" + + "Specify a number between %s - %s", taskId, 1, taskListSize + 1)); + } + + /** + * Notifies the user about the tasks that contains the given keyword. + * + * @param matchedTasks the list of tasks that matches the given keyword. + * @param keyword the keyword to match the tasks against. + * @return A string representing the list of tasks that matches the given keyword. If no tasks are found, + * return a string indicating that there are no tasks that matches the keyword. + */ + public String formatFoundTasks(List matchedTasks, String keyword) { + if (matchedTasks.isEmpty()) { + return outputService.echo(String.format("No tasks contains the keyword: %s! :<", keyword)); + } + List displayText = new ArrayList<>(); + String taskWord = matchedTasks.size() == 1 + ? "task" + : "tasks"; + displayText.add(String.format("Found %s matching %s in your list!", matchedTasks.size(), taskWord)); + displayText.addAll(outputService.formatTaskList(matchedTasks)); + return outputService.echo(displayText); + } +} diff --git a/src/main/java/duke/tasks/DeadlineTask.java b/src/main/java/duke/tasks/DeadlineTask.java new file mode 100644 index 0000000000..2dca6e6502 --- /dev/null +++ b/src/main/java/duke/tasks/DeadlineTask.java @@ -0,0 +1,43 @@ +package duke.tasks; + +import java.time.LocalDateTime; + +import duke.util.TimeUtil; + +/** + * Represents a task with a deadline in the Duke application. + */ +public class DeadlineTask extends Task { + private LocalDateTime endDate; + + /** + * Constructs a DeadlineTask. + * + * @param taskName The name of the task. + * @param endDate The deadline of the task. + */ + public DeadlineTask(String taskName, LocalDateTime endDate) { + super(taskName, TaskType.DEADLINE); + this.endDate = endDate; + } + + /** + * Retrieves the end date of the task. + * + * @return The end date of the task. + */ + public LocalDateTime getEndDate() { + return this.endDate; + } + + /** + * Returns a string representation of the deadline task. + * + * @return A string detailing the task. + */ + @Override + public String toString() { + String formattedEndDate = TimeUtil.formatLocalDateTime(endDate); + return String.format("%s (by: %s)", super.toString(), formattedEndDate); + } +} diff --git a/src/main/java/duke/tasks/EventTask.java b/src/main/java/duke/tasks/EventTask.java new file mode 100644 index 0000000000..ba7d0fff94 --- /dev/null +++ b/src/main/java/duke/tasks/EventTask.java @@ -0,0 +1,38 @@ +package duke.tasks; + +import java.time.LocalDateTime; + +import duke.util.TimeUtil; + +/** + * Represents an event task in the Duke application. + */ +public class EventTask extends Task { + private LocalDateTime startDate; + private LocalDateTime endDate; + + /** + * Constructs an EventTask. + * + * @param taskName The name of the task. + * @param startDate The start date of the event. + * @param endDate The end date of the event. + */ + public EventTask(String taskName, LocalDateTime startDate, LocalDateTime endDate) { + super(taskName, TaskType.EVENT); + this.startDate = startDate; + this.endDate = endDate; + } + + /** + * Returns a string representation of the event task. + * + * @return A string detailing the task. + */ + @Override + public String toString() { + String formattedStartDate = TimeUtil.formatLocalDateTime(startDate); + String formattedEndDate = TimeUtil.formatLocalDateTime(endDate); + return String.format("%s (from: %s to: %s)", super.toString(), formattedStartDate, formattedEndDate); + } +} diff --git a/src/main/java/duke/tasks/Task.java b/src/main/java/duke/tasks/Task.java new file mode 100644 index 0000000000..acd29cb743 --- /dev/null +++ b/src/main/java/duke/tasks/Task.java @@ -0,0 +1,46 @@ +package duke.tasks; + +import java.io.Serializable; + +/** + * Represents a general task in the Duke application. + */ +public abstract class Task implements Serializable { + private String taskName; + private TaskType taskType; + private boolean isDone; + + /** + * Constructs a Task. + * + * @param taskName The name of the task. + * @param taskType The type of the task (e.g., TODO, DEADLINE). + */ + public Task(String taskName, TaskType taskType) { + this.taskName = taskName; + this.taskType = taskType; + this.isDone = false; + } + + public String getTaskName() { + return this.taskName; + } + + public boolean isDone() { + return this.isDone; + } + + public void markAsDone() { + this.isDone = true; + } + + public void markAsNotDone() { + this.isDone = false; + } + + @Override + public String toString() { + String taskStatus = isDone ? "[X]" : "[ ]"; + return String.format("[%s]%s %s", taskType.getTaskType(), taskStatus, taskName); + } +} diff --git a/src/main/java/duke/tasks/TaskList.java b/src/main/java/duke/tasks/TaskList.java new file mode 100644 index 0000000000..f7d97703b0 --- /dev/null +++ b/src/main/java/duke/tasks/TaskList.java @@ -0,0 +1,132 @@ +package duke.tasks; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import duke.exception.DukeStorageException; +import duke.service.StorageService; + +/** + * Represents a list of tasks that supports various task management operations. + * Integrates with a storage service to ensure persistence of tasks. + */ +public class TaskList { + private List taskList; + private StorageService storageService; + + /** + * Constructs a new TaskList instance. + */ + public TaskList() { + this.taskList = new ArrayList<>(); + } + + /** + * Loads the stored tasks from the storageService into the taskList. + * + * @param storageService the given storageService. + */ + public void loadFromStorage(StorageService storageService) { + this.storageService = storageService; + this.taskList = new ArrayList<>(storageService.loadTasks()); + } + + /** + * Adds a new task to the list and updates the storage. + * + * @param task The task to be added. + * @return True if the task was added successfully, false otherwise. + * @throws DukeStorageException If an error occurs while saving to storage. + */ + public boolean addTask(Task task) throws DukeStorageException { + assert task != null : "task should not be null!"; + storageService.saveTask(task); + return this.taskList.add(task); + } + + /** + * Deletes a task based on its index in the list and updates the storage. + * + * @param index The index of the task to be deleted. + * @return An optional containing the deleted task, empty if the index was invalid. + * @throws DukeStorageException If an error occurs while updating storage. + */ + public Optional deleteTask(int index) throws DukeStorageException { + if (index < 0 || index >= taskList.size()) { + return Optional.empty(); + } + storageService.deleteTask(index); + Task removedTask = taskList.remove(index); + assert removedTask != null : "There should not have been null tasks in the list!"; + return Optional.of(removedTask); + } + + /** + * Marks a task as completed based on its index and updates the storage. + * + * @param index The index of the task to be marked. + * @return An optional containing the marked task, empty if the index was invalid. + * @throws DukeStorageException If an error occurs while updating storage. + */ + public Optional markTask(int index) throws DukeStorageException { + if (index < 0 || index >= taskList.size()) { + return Optional.empty(); + } + Task task = taskList.get(index); + assert task != null : "There should not have been null tasks in the list!"; + task.markAsDone(); + storageService.saveTasks(taskList); + return Optional.of(task); + } + + /** + * Unmarks a task as completed based on its index and updates the storage. + * + * @param index The index of the task to be unmarked. + * @return An optional containing the unmarked task, empty if the index was invalid. + * @throws DukeStorageException If an error occurs while updating storage. + */ + public Optional unmarkTask(int index) throws DukeStorageException { + if (index < 0 || index >= taskList.size()) { + return Optional.empty(); + } + Task task = taskList.get(index); + assert task != null : "There should not have been null tasks in the list!"; + task.markAsNotDone(); + storageService.saveTasks(taskList); + return Optional.of(task); + } + + /** + * Returns a List of tasks in the taskList with taskName that matches the given keyword. + * + * @param keyword the keyword to match in the taskList. + * @return the list of tasks that contains the keyword in their taskName. + */ + public List searchTasks(String keyword) { + return taskList.stream() + .filter(task -> task.getTaskName().toLowerCase().contains(keyword.toLowerCase())) + .collect(Collectors.toList()); + } + + /** + * Retrieves the list of tasks currently managed. + * + * @return A list of tasks. + */ + public List getTaskList() { + return taskList; + } + + /** + * Returns the total number of tasks currently managed. + * + * @return Number of tasks. + */ + public int getNumberOfTasks() { + return taskList.size(); + } + +} diff --git a/src/main/java/duke/tasks/TaskType.java b/src/main/java/duke/tasks/TaskType.java new file mode 100644 index 0000000000..27f258cb91 --- /dev/null +++ b/src/main/java/duke/tasks/TaskType.java @@ -0,0 +1,30 @@ +package duke.tasks; + +/** + * Enumerates the different types of tasks available in the Duke application. + */ +public enum TaskType { + TODO("T"), + DEADLINE("D"), + EVENT("E"); + + private final String taskType; + + /** + * Constructs a TaskType enumeration. + * + * @param taskType The type of the task (e.g., "T" for TO-DO). + */ + TaskType(String taskType) { + this.taskType = taskType; + } + + /** + * Retrieves the type of the task. + * + * @return A string representing the type. + */ + public String getTaskType() { + return taskType; + } +} diff --git a/src/main/java/duke/tasks/TodoTask.java b/src/main/java/duke/tasks/TodoTask.java new file mode 100644 index 0000000000..62b6616154 --- /dev/null +++ b/src/main/java/duke/tasks/TodoTask.java @@ -0,0 +1,16 @@ +package duke.tasks; + +/** + * Represents a 'To-Do' task in the Duke application. + */ +public class TodoTask extends Task { + + /** + * Constructs a TodoTask. + * + * @param taskName The name of the task. + */ + public TodoTask(String taskName) { + super(taskName, TaskType.TODO); + } +} diff --git a/src/main/java/duke/util/TimeUtil.java b/src/main/java/duke/util/TimeUtil.java new file mode 100644 index 0000000000..c3beafaf33 --- /dev/null +++ b/src/main/java/duke/util/TimeUtil.java @@ -0,0 +1,149 @@ +package duke.util; + +import java.time.DayOfWeek; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Locale; + +import duke.exception.TimeUtilException; + +/** + * Provides utility functions to handle and format time-related inputs. + *

+ * This utility class provides multiple date and time formats for parsing, + * which can be helpful in accommodating various user inputs. + *

+ */ +public class TimeUtil { + private static final DateTimeFormatter[] DATE_TIME_FORMATTERS = { + DateTimeFormatter.ofPattern("yyyy-MM-dd HHmm"), + DateTimeFormatter.ofPattern("yyyyMMdd HHmm") + }; + + private static final DateTimeFormatter[] DATE_ONLY_FORMATTERS = { + DateTimeFormatter.ISO_LOCAL_DATE, + DateTimeFormatter.BASIC_ISO_DATE, + DateTimeFormatter.ofPattern("d MMM yyyy", Locale.ENGLISH), + DateTimeFormatter.ofPattern("d MMMM yyyy", Locale.ENGLISH) + }; + + private static final DateTimeFormatter DISPLAY_FORMATTER = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm"); + + // Private constructor to prevent instantiation + private TimeUtil() {} + + /** + * Parses the provided date-time string to a LocalDateTime object. + *

+ * The function tries various date-time patterns to find a match. + * If none of the patterns match, it throws a TimeUtilException. + *

+ * + * @param input The date-time string to parse. + * @return A LocalDateTime object. + * @throws TimeUtilException If the input string cannot be parsed. + */ + public static LocalDateTime parseDateTimeString(String input) throws TimeUtilException { + LocalDateTime dateTime = handleSpecialStrings(input); + if (dateTime != null) { + return dateTime; + } + for (DateTimeFormatter formatter : DATE_TIME_FORMATTERS) { + try { + return LocalDateTime.parse(input, formatter); + } catch (DateTimeParseException ignored) { + // try next formatter + } + } + for (DateTimeFormatter formatter : DATE_ONLY_FORMATTERS) { + try { + LocalDate parsedDate = LocalDate.parse(input, formatter); + return LocalDateTime.of(parsedDate, LocalDateTime.now().toLocalTime()); + } catch (DateTimeParseException ignored) { + // try next formatter + } + } + throw new TimeUtilException(getHelpMessage()); + } + + /** + * Formats a LocalDateTime object to a human-readable string. + * + * @param localDate The LocalDateTime object to format. + * @return A string representation of the LocalDateTime object. + */ + public static String formatLocalDateTime(LocalDateTime localDate) { + return localDate.format(DISPLAY_FORMATTER); + } + + /** + * Returns a help message explaining valid date formats. + * + * @return A string containing a list of valid date formats. + */ + public static String getHelpMessage() { + return "Invalid date format! Please use one of the following formats:" + + "\n- yyyy-MM-dd HHmm (e.g. 2023-05-28 1800)" + + "\n- yyyyMMdd HHmm (e.g. 2023-05-28 1800)" + + "\n- yyyy-MM-dd (e.g. 2023-05-28)" + + "\n- yyyymmdd (e.g. 20230528)" + + "\n- d MMM yyyy (e.g. 1 Jan 2023)" + + "\n- d MMMM yyyy (e.g. 1 January 2023)" + + "\nOr use special terms like:" + + "\n- today" + + "\n- tomorrow" + + "\n- monday (for the next Monday)" + + "\n- tuesday (for the next Tuesday)" + + "\n- ... (similarly for other days of the week)"; + } + + /** + * Handles special string inputs, converting them to LocalDateTime. + *

+ * The function currently supports 'today' and 'tomorrow' as special strings. + *

+ * + * @param input The special string input. + * @return A LocalDateTime representation of the input, or null if the input is not special. + */ + private static LocalDateTime handleSpecialStrings(String input) { + switch (input.toLowerCase()) { + case "today": + return LocalDateTime.now().withHour(23).withMinute(59); + case "tomorrow": + return LocalDateTime.now().plusDays(1).withHour(23).withMinute(59); + case "monday": + case "tuesday": + case "wednesday": + case "thursday": + case "friday": + case "saturday": + case "sunday": + return getNextDayOfWeek(DayOfWeek.valueOf(input.toUpperCase())); + default: + return null; + } + } + + /** + * Returns the LocalDateTime of the next occurrence of the specified day of the week. + *

+ * This method calculates the number of days between the current day and the desired day of the week. + * If the desired day is the same as the current day, it returns the date of the next week's occurrence. + *

+ * + * @param desiredDay The desired day of the week as a DayOfWeek enum value. + * @return A LocalDateTime representing the next occurrence of the desired day, with the time set to 23:59. + */ + private static LocalDateTime getNextDayOfWeek(DayOfWeek desiredDay) { + LocalDateTime now = LocalDateTime.now(); + int daysUntilDesired = desiredDay.getValue() - now.getDayOfWeek().getValue(); + if (daysUntilDesired <= 0) { // if today is the desired day or a later day in the week + daysUntilDesired += 7; // get the next occurrence of the desired day + } + return now.plusDays(daysUntilDesired).withHour(23).withMinute(59); + } + +} diff --git a/src/main/resources/images/DaDuke.png b/src/main/resources/images/DaDuke.png new file mode 100644 index 0000000000..c72c1398cb Binary files /dev/null and b/src/main/resources/images/DaDuke.png differ diff --git a/src/main/resources/images/DaUser.png b/src/main/resources/images/DaUser.png new file mode 100644 index 0000000000..b7b421504d 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..2da5ef8ddd --- /dev/null +++ b/src/main/resources/view/DialogBox.fxml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + \ 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 0000000000..23ed6def91 --- /dev/null +++ b/src/main/resources/view/MainWindow.fxml @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + +