diff --git a/.gitignore b/.gitignore index 2873e189e1..4c39274aa4 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,9 @@ bin/ /text-ui-test/ACTUAL.TXT text-ui-test/EXPECTED-UNIX.TXT + +# Java class files +*.class + +# Data folder for csv +/data diff --git a/README.md b/README.md index 8715d4d915..4aae9e9697 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,87 @@ -# Duke project template - -This is a project template for a greenfield Java project. It's named after the Java mascot _Duke_. Given below are instructions on how to use it. - -## Setting up in Intellij - -Prerequisites: JDK 11, update Intellij to the most recent version. - -1. Open Intellij (if you are not in the welcome screen, click `File` > `Close Project` to close the existing project first) -1. Open the project into Intellij as follows: - 1. Click `Open`. - 1. Select the project directory, and click `OK`. - 1. If there are any further prompts, accept the defaults. -1. Configure the project to use **JDK 11** (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: - ``` - Hello from - ____ _ - | _ \ _ _| | _____ - | | | | | | | |/ / _ \ - | |_| | |_| | < __/ - |____/ \__,_|_|\_\___| - ``` +# Duke User Guide + +Welcome to the Duke the Chatbot! This chatbot is designed to help you store and display information about your upcoming events using a Command Line Interface (CLI). Below is a list of available commands and their descriptions: + +## Available Commands + +### 1. List + +- Command: `list` +- Parameters: None +- Description: List all upcoming events. +- Usage: `list` + +### 2. Mark + +- Command: `mark (i)` +- Parameters: + - `i`: The index of the event to mark (must be an integer). +- Description: Mark the specified event in the list of events. +- Usage: `mark 1` (to mark the first event) + +### 3. Unmark + +- Command: `unmark (i)` +- Parameters: + - `i`: The index of the event to unmark (must be an integer). +- Description: Unmark the specified event. +- Usage: `unmark 1` (to unmark the first event) + +### 4. Todo + +- Command: `todo (name)` +- Parameters: + - `name`: The name of the todo event (represented by a string). +- Description: Add a todo event with the provided name. +- Usage: `todo Buy groceries` + +### 5. Event + +- Command: `event (name) /from (datetime) /to (datetime)` +- Parameters: + - `name`: The name of the event. + - `datetime`: The start and end date and time of the event. +- Description: Add an event with a name, start date, and end date. +- Usage: `event Birthday Party /from 2023-10-15 15:00 /to 2023-10-15 18:00` + +### 6. Deadline + +- Command: `deadline (name) /by (datetime)` +- Parameters: + - `name`: The name of the deadline event. + - `datetime`: The deadline date and time. +- Description: Add a deadline event with a name and a specified deadline. +- Usage: `deadline Submit Report /by 2023-11-01 23:59` + +### 7. Find + +- Command: `find (name)` +- Parameters: + - `name`: The keyword to search for within event names. +- Description: Find event names that match the provided string. +- Usage: `find Party` + +### 8. Upcoming + +- Command: `upcoming` +- Parameters: None +- Description: List all events in ascending order of their datetime. +- Usage: `upcoming` + +### 9. Bye + +- Command: `bye` +- Parameters: None +- Description: Exit the program. +- Usage: `bye` + +## Example Usage + +- To list all upcoming events: `list` +- To mark the first event: `mark 1` +- To add a todo event: `todo Buy groceries` +- To add an event with a specific date and time: `event Birthday Party /from 2023-10-15 15:00 /to 2023-10-15 18:00` +- To find events with the keyword "Party" in their names: `find Party` +- To exit the program: `bye` + +Feel free to use these commands to manage your upcoming events effectively with the chatbot. Enjoy using Duke! \ No newline at end of file diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..75fcee2ea4 --- /dev/null +++ b/build.gradle @@ -0,0 +1,65 @@ +plugins { + id 'checkstyle' + id 'java' + id 'application' + id 'com.github.johnrengelman.shadow' version '7.1.2' +} + +repositories { + mavenCentral() +} + +checkstyle { + toolVersion = '10.2' +} + +repositories { + mavenCentral() +} + +dependencies { + 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' + 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' +} + +test { + useJUnitPlatform() + + testLogging { + events "passed", "skipped", "failed" + + showExceptions true + exceptionFormat "full" + showCauses true + showStackTraces true + showStandardStreams = false + } +} + +application { + mainClass.set("duke.Duke") +} + +shadowJar { + archiveFileName = "duke.jar" + //archiveClassifier = null + //dependsOn("distZip", "distTar") +} + +run{ + standardInput = System.in +} diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml new file mode 100644 index 0000000000..d1399810b5 --- /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..dcaa1af3c3 --- /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..4aae9e9697 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,29 +1,87 @@ -# User Guide +# Duke User Guide -## Features +Welcome to the Duke the Chatbot! This chatbot is designed to help you store and display information about your upcoming events using a Command Line Interface (CLI). Below is a list of available commands and their descriptions: -### Feature-ABC +## Available Commands -Description of the feature. +### 1. List -### Feature-XYZ +- Command: `list` +- Parameters: None +- Description: List all upcoming events. +- Usage: `list` -Description of the feature. +### 2. Mark -## Usage +- Command: `mark (i)` +- Parameters: + - `i`: The index of the event to mark (must be an integer). +- Description: Mark the specified event in the list of events. +- Usage: `mark 1` (to mark the first event) -### `Keyword` - Describe action +### 3. Unmark -Describe the action and its outcome. +- Command: `unmark (i)` +- Parameters: + - `i`: The index of the event to unmark (must be an integer). +- Description: Unmark the specified event. +- Usage: `unmark 1` (to unmark the first event) -Example of usage: +### 4. Todo -`keyword (optional arguments)` +- Command: `todo (name)` +- Parameters: + - `name`: The name of the todo event (represented by a string). +- Description: Add a todo event with the provided name. +- Usage: `todo Buy groceries` -Expected outcome: +### 5. Event -Description of the outcome. +- Command: `event (name) /from (datetime) /to (datetime)` +- Parameters: + - `name`: The name of the event. + - `datetime`: The start and end date and time of the event. +- Description: Add an event with a name, start date, and end date. +- Usage: `event Birthday Party /from 2023-10-15 15:00 /to 2023-10-15 18:00` -``` -expected output -``` +### 6. Deadline + +- Command: `deadline (name) /by (datetime)` +- Parameters: + - `name`: The name of the deadline event. + - `datetime`: The deadline date and time. +- Description: Add a deadline event with a name and a specified deadline. +- Usage: `deadline Submit Report /by 2023-11-01 23:59` + +### 7. Find + +- Command: `find (name)` +- Parameters: + - `name`: The keyword to search for within event names. +- Description: Find event names that match the provided string. +- Usage: `find Party` + +### 8. Upcoming + +- Command: `upcoming` +- Parameters: None +- Description: List all events in ascending order of their datetime. +- Usage: `upcoming` + +### 9. Bye + +- Command: `bye` +- Parameters: None +- Description: Exit the program. +- Usage: `bye` + +## Example Usage + +- To list all upcoming events: `list` +- To mark the first event: `mark 1` +- To add a todo event: `todo Buy groceries` +- To add an event with a specific date and time: `event Birthday Party /from 2023-10-15 15:00 /to 2023-10-15 18:00` +- To find events with the keyword "Party" in their names: `find Party` +- To exit the program: `bye` + +Feel free to use these commands to manage your upcoming events effectively with the chatbot. Enjoy using Duke! \ No newline at end of file diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..a205efa1b0 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/Duke.java b/src/main/java/duke/Duke.java new file mode 100644 index 0000000000..59e49284db --- /dev/null +++ b/src/main/java/duke/Duke.java @@ -0,0 +1,19 @@ +package duke; + +import duke.utils.Session; +import javafx.application.Application; + +/** + * The Duke class serves as the entry point to the Duke application. + * It creates an instance of the Session class and starts the chatbot session. + */ +public class Duke { + /** + * The main method that launches the Duke application. + * + * @param args Command-line arguments (not used). + */ + public static void main(String[] args) { + Application.launch(Session.class, args); + } +} diff --git a/src/main/java/duke/Utils/Command.java b/src/main/java/duke/Utils/Command.java new file mode 100644 index 0000000000..46121bf31d --- /dev/null +++ b/src/main/java/duke/Utils/Command.java @@ -0,0 +1,116 @@ +package duke.utils; + +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +/** + * The Command class provides utility methods for parsing and validating + * command arguments in a specific format. + */ +public class Command { + // Regular expression pattern for date and time in the format "YYYY-MM-DD HH:mm" + private static final Pattern DATE_RX = Pattern.compile( + "^" + + "(" + + "((2000|2400|2800|(19|2[0-9])(0[48]|[2468][048]|[13579][26]))-02-29)" + + "|(((19|2[0-9])[0-9]{2})-02-(0[1-9]|1[0-9]|2[0-8]))" + + "|(((19|2[0-9])[0-9]{2})-(0[13578]|10|12)-(0[1-9]|[12][0-9]|3[01]))" + + "|(((19|2[0-9])[0-9]{2})-(0[469]|11)-(0[1-9]|[12][0-9]|30))" + + ")" + + "\\s" + + "([01]?[0-9]|2[0-3]):[0-5][0-9]" + + "$" + ); // YYYY-MM-DD HH:mm + + /** + * Enumeration representing the types of command arguments. + */ + enum Type { + NONE, + INTEGER, + STRING, + DATETIME + } + + /** + * Extracts the value of a specific argument from an input string. + * + * @param input The input string containing arguments. + * @param targetArg The name of the argument to extract. + * @return The value of the specified argument. + */ + private static String getArg(String input, String targetArg) { + String[] args = input.split("/"); + for (String arg : args) { + String[] words = arg.split(" "); + String argName = words[0]; + if (argName.equals(targetArg)) { + return Arrays.stream(words).skip(1).collect(Collectors.joining(" ")); + } + } + return ""; + } + + /** + * Validates and retrieves a string argument from the input. + * + * @param input The input string containing arguments. + * @param argName The name of the string argument to validate and retrieve. + * @return The validated string argument value. + * @throws InvalidArgumentException if the argument is missing or empty. + */ + protected static String assertString(String input, String argName) throws InvalidArgumentException { + String arg = Command.getArg(input, argName); + if (arg.isEmpty()) { + throw new InvalidArgumentException(argName, Type.STRING); + } + assert arg != ""; + return arg; + } + + /** + * Validates and retrieves an integer argument from the input. + * + * @param input The input string containing arguments. + * @param argName The name of the integer argument to validate and retrieve. + * @return The validated integer argument value. + * @throws InvalidArgumentException if the argument is missing, empty, or not a valid integer. + */ + protected static Integer assertInteger(String input, String argName) throws InvalidArgumentException { + try { + String arg = Command.getArg(input, argName); + if (arg.isEmpty()) { + throw new InvalidArgumentException(argName, Type.INTEGER); + } + assert arg != ""; + return Integer.parseInt(arg); + } catch (NumberFormatException e) { + throw new InvalidArgumentException(argName, Type.INTEGER); + } + } + + /** + * Validates and retrieves a LocalDateTime argument from the input. + * + * @param input The input string containing arguments. + * @param argName The name of the DateTime argument to validate and retrieve. + * @return The validated LocalDateTime argument value. + * @throws InvalidArgumentException if the argument is missing or not in the expected format. + */ + protected static LocalDateTime assertDateTime(String input, String argName) throws InvalidArgumentException { + String arg = Command.getArg(input, argName); + System.out.println(arg + '|'); + if (!Command.DATE_RX.matcher(arg).matches()) { + throw new InvalidArgumentException(argName, Type.DATETIME); + } + String[] timeSplit = arg.split(" "); + CharSequence timeSequence = + timeSplit[0] + + "T" + + timeSplit[1] + + ":00"; + return LocalDateTime.parse(timeSequence); + } +} diff --git a/src/main/java/duke/Utils/CommandNotFoundException.java b/src/main/java/duke/Utils/CommandNotFoundException.java new file mode 100644 index 0000000000..eae88909bd --- /dev/null +++ b/src/main/java/duke/Utils/CommandNotFoundException.java @@ -0,0 +1,15 @@ +package duke.utils; + +/** + * The CommandNotFoundException class represents an exception that is thrown when + * a command is not found or recognized by the Duke application. + */ +public class CommandNotFoundException extends DukeException { + /** + * Constructs a new CommandNotFoundException with a default error message. + * The error message indicates that there is no such command. + */ + protected CommandNotFoundException() { + super("I'm sorry, but there is no such command."); + } +} diff --git a/src/main/java/duke/Utils/Deadline.java b/src/main/java/duke/Utils/Deadline.java new file mode 100644 index 0000000000..b0d3992072 --- /dev/null +++ b/src/main/java/duke/Utils/Deadline.java @@ -0,0 +1,85 @@ +package duke.utils; + +import java.time.LocalDateTime; + +/** + * The Deadline class represents a task with a deadline in the Duke application. + * It extends the Task class and includes additional information about the deadline. + */ +public class Deadline extends Task { + + private LocalDateTime start; + + /** + * Constructs a new Deadline object with the specified title and start date and time. + * + * @param title The title of the deadline task. + * @param start The date and time of the deadline. + */ + protected Deadline(String title, LocalDateTime start) { + super(title, Task.Type.DEADLINE); + this.start = start; + } + + /** + * Constructs a new Deadline object with the specified title, marked status, and start date and time. + * + * @param title The title of the deadline task. + * @param marked A boolean indicating whether the task is marked as completed. + * @param start The date and time of the deadline. + */ + protected Deadline(String title, boolean marked, LocalDateTime start) { + this(title, start); + if (marked) { + this.mark(); + } + } + + /** + * Creates a new Deadline object from an array of arguments. + * + * @param args An array of strings containing information to create a Deadline object. + * @return A new Deadline object created from the provided arguments. + */ + protected static Deadline of(String[] args) { + boolean marked = FileIO.assertBoolean(args[1]); + String title = FileIO.assertString(args[2]); + LocalDateTime start = FileIO.assertDateTime(args[3]); + return new Deadline(title, marked, start); + } + + /** + * Converts the Deadline object to a CSV (Comma-Separated Values) string. + * + * @return A CSV string representation of the Deadline object. + */ + @Override + public String toCsv() { + return FileIO.joinCsv( + this.type(), + this.marked(), + this.name(), + Task.dateToString(start) + ); + } + + /** + * Returns the start of the deadline + * + * @return A LocalDateTime representation of the start of deadline + */ + @Override + public LocalDateTime getDeadline() { + return this.start; + } + + /** + * Returns a string representation of the Deadline object, including its type and deadline information. + * + * @return A string representation of the Deadline object. + */ + @Override + public String toString() { + return this.type() + super.toString() + " (by: " + Task.dateToString(start) + ")"; + } +} diff --git a/src/main/java/duke/Utils/DukeException.java b/src/main/java/duke/Utils/DukeException.java new file mode 100644 index 0000000000..15a2ab7b9d --- /dev/null +++ b/src/main/java/duke/Utils/DukeException.java @@ -0,0 +1,30 @@ +package duke.utils; + +/** + * The DukeException class is a custom runtime exception class for handling exceptions + * specific to the Duke application. + * It extends the RuntimeException class and includes a custom error message. + */ +public class DukeException extends RuntimeException { + + private String errorMessage; + + /** + * Constructs a new DukeException with a custom error message. + * + * @param errorMessage The custom error message to be associated with the exception. + */ + protected DukeException(String errorMessage) { + this.errorMessage = errorMessage; + } + + /** + * Returns a string representation of the DukeException, including an error message. + * + * @return A string containing the error message preceded by "OOPS!!!". + */ + @Override + public String toString() { + return "OOPS!!! " + errorMessage; + } +} diff --git a/src/main/java/duke/Utils/Event.java b/src/main/java/duke/Utils/Event.java new file mode 100644 index 0000000000..0fe9ab99e4 --- /dev/null +++ b/src/main/java/duke/Utils/Event.java @@ -0,0 +1,96 @@ +package duke.utils; + +import java.time.LocalDateTime; + +/** + * The Event class represents a task with a specific start and end date and time in the Duke application. + * It extends the Task class and includes additional information about the event. + */ +public class Event extends Task { + + private LocalDateTime start; + private LocalDateTime end; + + /** + * Constructs a new Event object with the specified title, start date and time, and end date and time. + * + * @param title The title of the event task. + * @param start The date and time when the event starts. + * @param end The date and time when the event ends. + */ + protected Event(String title, LocalDateTime start, LocalDateTime end) { + super(title, Task.Type.EVENT); + this.start = start; + this.end = end; + } + + /** + * Constructs a new Event object with the specified title, marked status, start date and time, + * and end date and time. + * + * @param title The title of the event task. + * @param marked A boolean indicating whether the task is marked as completed. + * @param start The date and time when the event starts. + * @param end The date and time when the event ends. + */ + protected Event(String title, boolean marked, LocalDateTime start, LocalDateTime end) { + this(title, start, end); + if (marked) { + this.mark(); + } + } + + /** + * Creates a new Event object from an array of arguments. + * + * @param args An array of strings containing information to create an Event object. + * @return A new Event object created from the provided arguments. + */ + protected static Event of(String[] args) { + boolean marked = FileIO.assertBoolean(args[1]); + String title = FileIO.assertString(args[2]); + LocalDateTime start = FileIO.assertDateTime(args[3]); + LocalDateTime end = FileIO.assertDateTime(args[4]); + return new Event(title, marked, start, end); + } + + /** + * Converts the Event object to a CSV (Comma-Separated Values) string. + * + * @return A CSV string representation of the Event object. + */ + @Override + public String toCsv() { + return FileIO.joinCsv( + this.type(), + this.marked(), + this.name(), + Task.dateToString(this.start), + Task.dateToString(this.end) + ); + } + + /** + * Returns the start of the event + * + * @return A LocalDateTime representation of the start of event + */ + @Override + public LocalDateTime getDeadline() { + return this.start; + } + + /** + * Returns a string representation of the Event object, including its type and event time information. + * + * @return A string representation of the Event object. + */ + @Override + public String toString() { + return this.type() + + super.toString() + + " (from: " + Task.dateToString(this.start) + + " to: " + Task.dateToString(this.end) + + ")"; + } +} diff --git a/src/main/java/duke/Utils/FileIO.java b/src/main/java/duke/Utils/FileIO.java new file mode 100644 index 0000000000..3905b0799b --- /dev/null +++ b/src/main/java/duke/Utils/FileIO.java @@ -0,0 +1,152 @@ +package duke.utils; + +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +/** + * The FileIO class provides utility methods for reading and writing data to/from files + * in the context of the Duke application. + */ +public class FileIO { + private static final String DELIMITER = "-|-"; + private static final String SPLIT_DELIMITER = "(-\\|-)"; + private static final Pattern DATE_REGEX = Pattern.compile( + "^" + + "(" + + "((2000|2400|2800|(19|2[0-9])(0[48]|[2468][048]|[13579][26]))-02-29)" + + "|(((19|2[0-9])[0-9]{2})-02-(0[1-9]|1[0-9]|2[0-8]))" + + "|(((19|2[0-9])[0-9]{2})-(0[13578]|10|12)-(0[1-9]|[12][0-9]|3[01]))" + + "|(((19|2[0-9])[0-9]{2})-(0[469]|11)-(0[1-9]|[12][0-9]|30))" + + ")" + + "\\s" + + "([01]?[0-9]|2[0-3]):[0-5][0-9]" + + "$" + ); // YYYY-MM-DD HH:mm + + /** + * Joins an array of objects into a single string, using the specified delimiter. + * + * @param str The objects to be joined. + * @return The joined string. + */ + protected static String joinCsv(Object... str) { + return Stream.of(str) + .map(Object::toString) + .collect(Collectors.joining(FileIO.DELIMITER)); + } + + /** + * Reads a list of CSV lines and converts them into a list of Task objects. + * + * @param lines The list of CSV lines to be parsed. + * @return A list of Task objects parsed from the CSV lines. + * @throws InvalidFileDataException if the data in the file is invalid or cannot be parsed. + */ + protected static ArrayList readCsv(ArrayList lines) throws InvalidFileDataException { + ArrayList tasks = new ArrayList<>(); + for (String line : lines) { + String[] args = line.split(FileIO.SPLIT_DELIMITER); + Task.Type type = Task.Type.of(args[0]); + assertParams(args, type); + switch(type) { + case TODO: + tasks.add(Todo.of(args)); + break; + case DEADLINE: + tasks.add(Deadline.of(args)); + break; + case EVENT: + tasks.add(Event.of(args)); + break; + default: + throw new InvalidFileDataException(); + } + } + return tasks; + } + + /** + * Asserts that the number of parameters in an argument array matches the expected number + * based on the Task type. + * + * @param args The argument array to be checked. + * @param type The Task type used to determine the expected number of parameters. + * @throws InvalidFileDataException if the number of parameters does not match the expected count. + */ + protected static void assertParams(String[] args, Task.Type type) throws InvalidFileDataException { + if (args.length != type.param()) { + throw new InvalidFileDataException(); + } + } + + /** + * Asserts that a string is not empty. + * + * @param input The input string to be checked. + * @return The input string if it is not empty. + * @throws InvalidFileDataException if the input string is empty. + */ + protected static String assertString(String input) throws InvalidFileDataException { + if (input.isEmpty()) { + throw new InvalidFileDataException(); + } + return input; + } + + /** + * Asserts that a string represents a boolean value ("true" or "false"). + * + * @param input The input string to be checked. + * @return The boolean value represented by the input string. + * @throws InvalidFileDataException if the input string does not represent a valid boolean. + */ + protected static boolean assertBoolean(String input) throws InvalidFileDataException { + if (input.equals("true")) { + return true; + } else if (input.equals("false")) { + return false; + } + throw new InvalidFileDataException(); + } + + /** + * Asserts that a string can be parsed into an integer. + * + * @param input The input string to be checked. + * @return The integer value parsed from the input string. + * @throws InvalidFileDataException if the input string cannot be parsed as an integer. + */ + protected static Integer assertInteger(String input) throws InvalidFileDataException { + try { + if (input.isEmpty()) { + throw new InvalidFileDataException(); + } + return Integer.parseInt(input); + } catch (NumberFormatException e) { + throw new InvalidFileDataException(); + } + } + + /** + * Asserts that a string matches a specific date and time format, particularly [YYYY-MM-DD HH:mm]. + * + * @param input The input string to be checked. + * @return The LocalDateTime object representing the parsed date and time. + * @throws InvalidFileDataException if the input string does not match the expected date and time format. + */ + protected static LocalDateTime assertDateTime(String input) throws InvalidFileDataException { + if (!FileIO.DATE_REGEX.matcher(input).matches()) { + throw new InvalidFileDataException(); + } + String[] timeSplit = input.split(" "); + CharSequence timeSequence = + timeSplit[0] + + "T" + + timeSplit[1] + + ":00"; + return LocalDateTime.parse(timeSequence); + } +} diff --git a/src/main/java/duke/Utils/Input.java b/src/main/java/duke/Utils/Input.java new file mode 100644 index 0000000000..abb0de07c8 --- /dev/null +++ b/src/main/java/duke/Utils/Input.java @@ -0,0 +1,51 @@ +package duke.utils; + +/** + * The Input class is responsible for handling user input and executing commands + * in the Duke application. + */ +public class Input { + private static final String FILE_PATH = "./data/duke.csv"; + private static final String FOLDER_PATH = "./data"; + private Storage storage; + private TaskList tasks; + private String input; + + /** + * Constructs a new Input object and initializes storage and task list. + */ + protected Input() { + this.storage = new Storage(Input.FILE_PATH, Input.FOLDER_PATH); + this.tasks = new TaskList(this.storage.load()); + } + + /** + * Reads a command from the user via the console input. + * + * @return The response generated after executing the user's command. + */ + protected Response command(String input) { + this.input = input; + return executeCommand(); + } + + /** + * Executes the user's command and returns a response. + * + * @return The response generated after executing the user's command. + */ + protected Response executeCommand() { + String command = this.input.split(" ")[0]; + if (command.equals("bye")) { + return Response.TERMINATE; + } + try { + Response response = this.tasks.execute(this.input, command); + this.storage.save(this.tasks.csvArray()); + return response; + } catch (DukeException e) { + return Response.generate(e.toString()); + } + } +} + diff --git a/src/main/java/duke/Utils/InvalidArgumentException.java b/src/main/java/duke/Utils/InvalidArgumentException.java new file mode 100644 index 0000000000..20f972cf73 --- /dev/null +++ b/src/main/java/duke/Utils/InvalidArgumentException.java @@ -0,0 +1,25 @@ +package duke.utils; + +import duke.utils.Command.Type; + +/** + * The InvalidArgumentException class represents an exception that is thrown when + * an invalid argument is provided in a user command in the Duke application. + * It extends the DukeException class and includes a custom error message. + */ +public class InvalidArgumentException extends DukeException { + /** + * Constructs a new InvalidArgumentException with a custom error message. + * + * @param arg The name of the argument. + * @param type The expected type of the argument. + */ + protected InvalidArgumentException(String arg, Type type) { + super(String.format( + "I'm sorry, but you have keyed in an invalid argument for the argType /%s. Try again with /%s [%s]", + arg, + arg, + type + )); + } +} diff --git a/src/main/java/duke/Utils/InvalidFileDataException.java b/src/main/java/duke/Utils/InvalidFileDataException.java new file mode 100644 index 0000000000..4f42427044 --- /dev/null +++ b/src/main/java/duke/Utils/InvalidFileDataException.java @@ -0,0 +1,16 @@ +package duke.utils; + +/** + * The InvalidFileDataException class represents an exception that is thrown when + * the integrity of file data is compromised or data cannot be parsed properly in the Duke application. + * It extends the DukeException class and includes a custom error message. + */ +public class InvalidFileDataException extends DukeException { + /** + * Constructs a new InvalidFileDataException with a custom error message + * indicating that the file data integrity is compromised. + */ + protected InvalidFileDataException() { + super("File data integrity is compromised."); + } +} diff --git a/src/main/java/duke/Utils/OutOfRangeException.java b/src/main/java/duke/Utils/OutOfRangeException.java new file mode 100644 index 0000000000..d1541ef6c3 --- /dev/null +++ b/src/main/java/duke/Utils/OutOfRangeException.java @@ -0,0 +1,14 @@ +package duke.utils; + +/** + * The OutOfRangeException class represents an exception that is thrown when + * a user provides an input number that is out of range of the current tasks. + */ +public class OutOfRangeException extends DukeException { + /** + * Constructs a new OutOfRangeException with a default error message. + */ + protected OutOfRangeException() { + super("I'm sorry, but your input number is out of range of the current tasks"); + } +} diff --git a/src/main/java/duke/Utils/Response.java b/src/main/java/duke/Utils/Response.java new file mode 100644 index 0000000000..05534cfa22 --- /dev/null +++ b/src/main/java/duke/Utils/Response.java @@ -0,0 +1,96 @@ +package duke.utils; + +import java.util.List; + +/** + * The Response class represents a response generated by the Duke application + * to provide feedback to the user. + */ +public class Response { + protected static final Response GREETINGS = Response.greeting(); + protected static final Response TERMINATE = Response.terminate(); + private static final String LINE = " ____________________________________________________________\n"; + private static final String TAB = " "; + private String messageOutput; + + private Response() { + this.messageOutput = ""; + } + + private void add(String message) { + this.messageOutput += Response.TAB + message + "\n"; + } + + /** + * Generates a response with a single message. + * + * @param message The message to be included in the response. + * @return A Response object containing the specified message. + */ + protected static Response generate(String message) { + Response response = new Response(); + response.add(message); + return response; + } + + /** + * Generates a response with an array of messages. + * + * @param messageArray An array of messages to be included in the response. + * @return A Response object containing the specified messages. + */ + protected static Response generate(String[] messageArray) { + Response response = new Response(); + for (int i = 0; i < messageArray.length; i++) { + response.add(messageArray[i]); + } + return response; + } + + /** + * Generates a response with a list of messages. + * + * @param messageList A list of messages to be included in the response. + * @return A Response object containing the specified messages. + */ + protected static Response generate(List messageList) { + Response response = new Response(); + for (String s : messageList) { + response.add(s); + } + return response; + } + + /** + * Generates a greeting response. + * + * @return A Response object with a standard greeting message. + */ + protected static Response greeting() { + Response response = new Response(); + response.add("Hello! I'm Duke"); + response.add("What can I do for you?"); + return response; + } + + /** + * Generates a termination response. + * + * @return A Response object with a standard termination message. + */ + protected static Response terminate() { + Response response = new Response(); + response.add("Bye. Hope to see you again soon!"); + return response; + } + + /** + * Returns a string representation of the response, including message content. + * + * @return A string representation of the response. + */ + @Override + public String toString() { + return Response.LINE + this.messageOutput + Response.LINE; + } +} diff --git a/src/main/java/duke/Utils/Session.java b/src/main/java/duke/Utils/Session.java new file mode 100644 index 0000000000..091ba376e7 --- /dev/null +++ b/src/main/java/duke/Utils/Session.java @@ -0,0 +1,237 @@ +package duke.utils; + +import javafx.application.Application; +import javafx.geometry.Insets; +import javafx.geometry.Pos; +import javafx.scene.Scene; +import javafx.scene.control.Button; +import javafx.scene.control.ScrollPane; +import javafx.scene.control.TextField; +import javafx.scene.image.Image; +import javafx.scene.image.ImageView; +import javafx.scene.layout.BorderPane; +import javafx.scene.layout.HBox; +import javafx.scene.layout.VBox; +import javafx.scene.text.Text; +import javafx.stage.Stage; + +/** + * The Session class represents a user session in the Duke application. + * It manages user input and responses during the session. + */ +public class Session extends Application { + private static final String IMG_DIR = "/img/"; + private static final String CHATBOT_AVATAR = IMG_DIR + "pb.jpg"; + private static final String USER_AVATAR = IMG_DIR + "rs.jpg"; + + private Response response; + private Input input; + private VBox chatBox; + private TextField inputField; + + /** + * The main method to launch the Duke application. + * + * @param args The command-line arguments. + */ + public static void main(String[] args) { + launch(args); + } + + @Override + public void start(Stage stage) { + initializeUI(stage); + this.input = new Input(); + } + + /** + * Initializes the user interface for the Duke application. + * + * @param primaryStage The primary stage for the application. + */ + public void initializeUI(Stage primaryStage) { + BorderPane root = createRootPane(); + Scene scene = new Scene(root, 500, 500); + setupPrimaryStage(primaryStage, scene); + setupInitialGreeting(); + } + + /** + * Creates the root BorderPane for the UI. + * + * @return The root BorderPane. + */ + private BorderPane createRootPane() { + BorderPane root = new BorderPane(); + chatBox = createChatBox(); + ScrollPane scrollPane = createScrollPane(); + inputField = createInputField(); + Button sendButton = createSendButton(); + HBox inputBox = createInputBox(sendButton); + + root.setCenter(scrollPane); + root.setBottom(inputBox); + + return root; + } + + /** + * Creates the chat box VBox. + * + * @return The chat box VBox. + */ + private VBox createChatBox() { + VBox chatBox = new VBox(10); + chatBox.setPadding(new Insets(10)); + return chatBox; + } + + /** + * Creates the scroll pane for the chat box. + * + * @return The scroll pane. + */ + private ScrollPane createScrollPane() { + ScrollPane scrollPane = new ScrollPane(chatBox); + scrollPane.setFitToWidth(true); + scrollPane.setFitToHeight(true); + return scrollPane; + } + + /** + * Creates the input field for user commands. + * + * @return The input field. + */ + private TextField createInputField() { + TextField inputField = new TextField(); + inputField.setPromptText("Enter your command..."); + return inputField; + } + + /** + * Creates the "Send" button. + * + * @return The "Send" button. + */ + private Button createSendButton() { + Button sendButton = new Button("Send"); + sendButton.setOnAction(event -> processUserInput()); + return sendButton; + } + + /** + * Creates the input box containing user image, input field, and "Send" button. + * + * @param sendButton The "Send" button. + * @return The input box. + */ + private HBox createInputBox(Button sendButton) { + ImageView userImageView = getAvatarImageView(USER_AVATAR); + HBox inputBox = new HBox(10); + inputBox.setPadding(new Insets(10)); + inputBox.getChildren().addAll(userImageView, inputField, sendButton); + return inputBox; + } + + /** + * Sets up the primary stage for the application. + * + * @param primaryStage The primary stage. + * @param scene The scene to be displayed. + */ + private void setupPrimaryStage(Stage primaryStage, Scene scene) { + primaryStage.setTitle("Duke Chatbot"); + primaryStage.setScene(scene); + primaryStage.show(); + } + + /** + * Displays the initial greeting in the chatbox. + */ + private void setupInitialGreeting() { + appendMessage(Response.GREETINGS.toString(), CHATBOT_AVATAR); + } + + /** + * Processes the user's input and displays responses in the chat interface. + */ + private void processUserInput() { + String userInput = inputField.getText().trim(); + if (!userInput.isEmpty()) { + appendMessage(userInput, USER_AVATAR); + Response response = input.command(userInput); + if (response == Response.TERMINATE) { + terminateApplication(); + } + appendMessage(response.toString(), CHATBOT_AVATAR); + inputField.clear(); + } + } + + /** + * Appends a message to the chat interface with an associated avatar. + * + * @param message The message to be displayed. + * @param imgSrc The source of the avatar image. + */ + private void appendMessage(String message, String imgSrc) { + ImageView avatarImageView = getAvatarImageView(imgSrc); + HBox messageBox = createMessageBox(message, avatarImageView, imgSrc); + chatBox.getChildren().add(messageBox); + } + + /** + * Creates a message box with an associated avatar for a message. + * + * @param message The message to be displayed. + * @param avatarImageView The avatar image associated with the message. + * @param imgSrc The source of the avatar image. + * @return The message box. + */ + private HBox createMessageBox(String message, ImageView avatarImageView, String imgSrc) { + Text messageText = new Text(message); + HBox messageContent; + HBox messageBox = new HBox(10); + + switch (imgSrc) { + case USER_AVATAR: + messageContent = new HBox(10, avatarImageView, messageText); + messageContent.setAlignment(Pos.BASELINE_LEFT); + messageBox.setStyle("-fx-background-color: #ddf2e4; -fx-padding: 10px;"); + break; + case CHATBOT_AVATAR: + messageContent = new HBox(10, messageText, avatarImageView); + messageContent.setAlignment(Pos.BASELINE_LEFT); + messageBox.setStyle("-fx-background-color: #fedada; -fx-padding: 10px;"); + break; + default: + throw new DukeException("?"); + } + + messageBox.getChildren().add(messageContent); + return messageBox; + } + + /** + * Terminates the Duke application. + */ + private void terminateApplication() { + System.exit(0); + } + + /** + * Retrieves an avatar ImageView from the specified image source. + * + * @param imgSrc The source of the avatar image. + * @return An ImageView containing the avatar image. + */ + private ImageView getAvatarImageView(String imgSrc) { + ImageView avatarImageView = new ImageView(new Image( + this.getClass().getResourceAsStream(imgSrc) + )); + avatarImageView.setFitWidth(50); + avatarImageView.setFitHeight(50); + return avatarImageView; + } +} diff --git a/src/main/java/duke/Utils/Storage.java b/src/main/java/duke/Utils/Storage.java new file mode 100644 index 0000000000..0304282099 --- /dev/null +++ b/src/main/java/duke/Utils/Storage.java @@ -0,0 +1,85 @@ +package duke.utils; + +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Scanner; + +/** + * The Storage class is responsible for reading and writing data to/from storage files + * in the Duke application. + */ +public class Storage { + enum Type { + INTEGER, + STRING + } + private final String filePath; + + /** + * Constructs a new Storage object with the specified file path and folder path. + * If the file does not exist, it creates the file. + * + * @param filePath The path to the storage file. + * @param folderPath The path to the folder where the storage file should be located. + */ + protected Storage(String filePath, String folderPath) { + this.filePath = filePath; + File file = new File(filePath); + try { + Files.createDirectories(Paths.get(folderPath)); + if (!file.exists()) { + file.createNewFile(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + /** + * Loads data from the storage file and returns a list of tasks. + * + * @return A list of Task objects loaded from the storage file. + */ + protected ArrayList load() { + ArrayList taskData = new ArrayList<>(); + try { + File file = new File(this.filePath); + Scanner scanner = new Scanner(file); + + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + taskData.add(line); + } + scanner.close(); + return FileIO.readCsv(taskData); + } catch (IOException e) { + e.printStackTrace(); + } catch (DukeException e) { + System.out.println(Response.generate(e.toString())); + } + return new ArrayList<>(); + } + + /** + * Saves a list of task data to the storage file. + * + * @param taskData A list of task data to be saved to the storage file. + */ + protected void save(ArrayList taskData) { + try { + FileWriter writer = new FileWriter(this.filePath); + + for (String line : taskData) { + writer.write(line + "\n"); + } + + writer.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/duke/Utils/Task.java b/src/main/java/duke/Utils/Task.java new file mode 100644 index 0000000000..4a92f3f044 --- /dev/null +++ b/src/main/java/duke/Utils/Task.java @@ -0,0 +1,147 @@ +package duke.utils; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * The Task class is an abstract base class for representing tasks in the Duke application. + */ +public abstract class Task { + enum Type { + TODO("[T]", 3), + DEADLINE("[D]", 4), + EVENT("[E]", 5); + + private final String name; + private final int numParams; + + private Type(String name, int numParams) { + this.name = name; + this.numParams = numParams; + } + + /** + * Retrieves the Type enum based on its name. + * + * @param name The name of the Type enum. + * @return The Type enum corresponding to the given name. + * @throws DukeException if no matching Type enum is found. + */ + protected static Type of(String name) throws DukeException { + for (Type type : values()) { + if (type.name.equals(name)) { + return type; + } + } + throw new InvalidFileDataException(); + } + + /** + * Gets the number of parameters expected for this task type. + * + * @return The number of parameters. + */ + protected int param() { + return this.numParams; + } + + @Override + public String toString() { + return this.name; + } + } + + private static final String MARKED_CHECKBOX = "[X]"; + private static final String UNMARKED_CHECKBOX = "[ ]"; + private static final DateTimeFormatter DATETIME_FORMAT = + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); + + private String title; + private Type type; + private boolean checked; + + /** + * Constructs a new Task object with a title and a task type. + * + * @param title The title of the task. + * @param type The type of the task. + */ + protected Task(String title, Type type) { + this.title = title; + this.type = type; + this.checked = false; + } + + /** + * Gets the title of the task. + * + * @return The title of the task. + */ + protected String name() { + return this.title; + } + + /** + * Gets the type of the task. + * + * @return The type of the task. + */ + protected Type type() { + return this.type; + } + + /** + * Checks if the task is marked (completed). + * + * @return true if the task is marked; false otherwise. + */ + protected boolean marked() { + return this.checked; + } + + /** + * Marks the task as completed. + */ + protected void mark() { + this.checked = true; + } + + /** + * Unmarks the task as completed. + */ + protected void unmark() { + this.checked = false; + } + + /** + * Converts the task to a CSV (Comma-Separated Values) string. + * + * @return A CSV string representation of the task. + */ + protected abstract String toCsv(); + + /** + * Gets the deadline of a Task, if any + * + * @return A LocalDateTime object representation of the task's urgency. + */ + protected abstract LocalDateTime getDeadline(); + + /** + * Converts a LocalDateTime object to a formatted string. + * + * @param datetime The LocalDateTime object to be converted. + * @return A formatted string representation of the date and time. + */ + protected static String dateToString(LocalDateTime datetime) { + return datetime.format(Task.DATETIME_FORMAT); + } + + @Override + public String toString() { + return String.format("%s %s", + this.checked ? Task.MARKED_CHECKBOX : Task.UNMARKED_CHECKBOX, + this.name() + ); + } +} diff --git a/src/main/java/duke/Utils/TaskList.java b/src/main/java/duke/Utils/TaskList.java new file mode 100644 index 0000000000..e5479db197 --- /dev/null +++ b/src/main/java/duke/Utils/TaskList.java @@ -0,0 +1,256 @@ +package duke.utils; + +import java.util.ArrayList; + +/** + * The TaskList class represents a list of tasks in the Duke application + * and provides methods to manage and manipulate these tasks. + */ +public class TaskList { + private ArrayList tasks; + + /** + * Enumeration representing various command types for task manipulation. + */ + enum Type { + MARK("mark"), + UNMARK("unmark"), + LIST("list"), + TODO("todo"), + DEADLINE("deadline"), + EVENT("event"), + DELETE("delete"), + FIND("find"), + UPCOMING("upcoming"), + NOTFOUND(""),; + + private final String name; + + private Type(String name) { + this.name = name; + } + + /** + * Retrieves the Type enum based on its name. + * + * @param name The name of the Type enum. + * @return The Type enum corresponding to the given name. + */ + protected static Type of(String name) { + for (Type type : values()) { + if (type.name.equals(name)) { + return type; + } + } + return NOTFOUND; + } + } + + /** + * Constructs a new TaskList object with an initial list of tasks. + * + * @param tasks The initial list of tasks. + */ + protected TaskList(ArrayList tasks) { + this.tasks = tasks; + } + + /** + * Converts the list of tasks to a list of CSV strings. + * + * @return A list of CSV strings representing the tasks. + */ + protected ArrayList csvArray() { + ArrayList csv = new ArrayList<>(); + for (Task task : this.tasks) { + csv.add(task.toCsv()); + } + return csv; + } + + /** + * Executes a user command and returns a response. + * + * @param input The user input command. + * @param command The command keyword extracted from the input. + * @return A Response object representing the response to the command. + * @throws DukeException if there's an error executing the command. + */ + protected Response execute(String input, String command) throws DukeException { + Task task; + + switch (Type.of(command)) { + case TODO: + task = new Todo(Command.assertString(input, command)); + break; + case DEADLINE: + task = new Deadline( + Command.assertString(input, command), + Command.assertDateTime(input, "by") + ); + break; + case EVENT: + task = new Event( + Command.assertString(input, command), + Command.assertDateTime(input, "from"), + Command.assertDateTime(input, "to") + ); + break; + case MARK: + return this.mark(Command.assertInteger(input, command)); + case UNMARK: + return this.unmark(Command.assertInteger(input, command)); + case DELETE: + return this.delete(Command.assertInteger(input, command)); + case LIST: + return this.list(); + case FIND: + return this.find(Command.assertString(input, command)); + case UPCOMING: + return this.listSortedTasks(); + default: + throw new CommandNotFoundException(); + } + this.tasks.add(task); + return Response.generate(new String[]{ + "Got it. I've added this task:", + " " + task.toString(), + String.format("Now you have %d tasks in the list.", tasks.size()) + }); + } + + /** + * Lists all tasks and returns a response. + * + * @return A Response object listing all tasks. + */ + protected Response list() { + ArrayList output = new ArrayList<>(); + output.add("Here are the tasks in your list:"); + int count = 0; + for (Task task : this.tasks) { + output.add(String.format("%d.%s", + ++count, + task.toString() + )); + } + return Response.generate(output); + } + + /** + * Checks if the given index is within a valid range. + * + * @param idx The index to check. + * @return true if the index is within a valid range; false otherwise. + */ + private boolean inRange(int idx) { + return (idx > 0 && this.tasks.size() > --idx); + } + + /** + * Marks a task as completed and returns a response. + * + * @param idx The index of the task to mark. + * @return A Response object indicating that the task has been marked as done. + * @throws DukeException if the task index is out of range. + */ + protected Response mark(int idx) throws DukeException { + ArrayList output = new ArrayList<>(); + if (!this.inRange(idx)) { + throw new OutOfRangeException(); + } + Task task = this.tasks.get(--idx); + task.mark(); + output.add("Nice! I've marked this task as done:"); + output.add(" " + task.toString()); + + return Response.generate(output); + } + + /** + * Unmarks a completed task and returns a response. + * + * @param idx The index of the task to unmark. + * @return A Response object indicating that the task has been marked as not done yet. + * @throws DukeException if the task index is out of range. + */ + protected Response unmark(int idx) throws DukeException { + ArrayList output = new ArrayList<>(); + if (!this.inRange(idx)) { + throw new OutOfRangeException(); + } + Task task = this.tasks.get(--idx); + task.unmark(); + output.add("OK, I've marked this task as not done yet:"); + output.add(" " + task.toString()); + + return Response.generate(output); + } + + /** + * Deletes a task and returns a response. + * + * @param idx The index of the task to delete. + * @return A Response object indicating that the task has been deleted. + * @throws DukeException if the task index is out of range. + */ + protected Response delete(int idx) throws DukeException { + ArrayList output = new ArrayList<>(); + if (!this.inRange(idx)) { + throw new OutOfRangeException(); + } + Task task = this.tasks.get(--idx); + output.add("Noted. I've removed this task:"); + output.add(" " + task.toString()); + this.tasks.remove(idx); + output.add(String.format("Now you have %d tasks in the list.", tasks.size())); + + return Response.generate(output); + } + + /** + * Searches for tasks in the task list that contain a specified keyword in their names. + * If any matching tasks are found, they are listed in the response. + * + * @param keyword The keyword to search for in task names. + * @return A Response object containing a list of matching tasks if found. + * @throws DukeException if no matching tasks are found. + */ + protected Response find(String keyword) throws DukeException { + ArrayList output = new ArrayList<>(); + output.add("Here are the matching tasks in your list:"); + + int count = 0; + for (Task task : this.tasks) { + if (task.name().contains(keyword)) { + output.add(String.format("%d.%s", ++count, task.toString())); + } + } + if (count == 0) { + throw new TaskNotFoundException(); + } + return Response.generate(output); + } + + /** + * Sorts the list of tasks by deadline and returns a response. + * + * @return A Response object listing tasks in descending urgency. + */ + @SuppressWarnings("unchecked") + protected Response listSortedTasks() { + ArrayList taskList = (ArrayList) this.tasks.clone(); + taskList.sort((Task l, Task r)-> l.getDeadline().isAfter(r.getDeadline()) ? 1 : -1); + + ArrayList output = new ArrayList<>(); + output.add("Here are your upcoming tasks, sorted in descending urgency:"); + int count = 0; + for (Task task : taskList) { + output.add(String.format("%d.%s", + ++count, + task.toString() + )); + } + return Response.generate(output); + } +} diff --git a/src/main/java/duke/Utils/TaskNotFoundException.java b/src/main/java/duke/Utils/TaskNotFoundException.java new file mode 100644 index 0000000000..42f9347fce --- /dev/null +++ b/src/main/java/duke/Utils/TaskNotFoundException.java @@ -0,0 +1,14 @@ +package duke.utils; + +/** + * The TaskNotFoundException class represents an exception that is thrown when + * a user provides a search keyword that does not match any of the current tasks. + */ +public class TaskNotFoundException extends DukeException { + /** + * Constructs a new TaskNotFoundException with a default error message. + */ + protected TaskNotFoundException() { + super("I'm sorry, but none of the task matches your search keyword"); + } +} diff --git a/src/main/java/duke/Utils/Todo.java b/src/main/java/duke/Utils/Todo.java new file mode 100644 index 0000000000..785f2cb4ca --- /dev/null +++ b/src/main/java/duke/Utils/Todo.java @@ -0,0 +1,71 @@ +package duke.utils; + +import java.time.LocalDateTime; + +/** + * The ToDo class represents a task of type "Todo" in the Duke application. + * It extends the Task class and provides specific functionality for Todo tasks. + */ +public class Todo extends Task { + + private static final LocalDateTime MAX_DATE = LocalDateTime.MAX; + + /** + * Constructs a new Todo object with a title. + * + * @param title The title of the Todo task. + */ + protected Todo(String title) { + super(title, Task.Type.TODO); + } + + /** + * Constructs a new Todo object with a title and a marked status. + * + * @param title The title of the Todo task. + * @param marked true if the task is marked as completed, false otherwise. + */ + protected Todo(String title, boolean marked) { + this(title); + if (marked) { + this.mark(); + } + } + + /** + * Creates a Todo object from an array of string arguments. + * + * @param args The array of string arguments containing task data. + * @return A Todo object created from the provided arguments. + * @throws InvalidFileDataException if the input arguments are invalid. + */ + protected static Todo of(String[] args) throws InvalidFileDataException { + boolean marked = FileIO.assertBoolean(args[1]); + String title = FileIO.assertString(args[2]); + return new Todo(title, marked); + } + + /** + * Converts the Todo object to a CSV (Comma-Separated Values) string. + * + * @return A CSV string representation of the Todo object. + */ + @Override + public String toCsv() { + return FileIO.joinCsv(this.type(), this.marked(), this.name()); + } + + /** + * Returns maximum date possible, since the deadline is non-existent + * @return A LocalDateTime representation of the maximum date possible + */ + @Override + public LocalDateTime getDeadline() { + return Todo.MAX_DATE; + } + + @Override + public String toString() { + return this.type() + super.toString(); + } +} diff --git a/src/main/resources/img/pb.jpg b/src/main/resources/img/pb.jpg new file mode 100644 index 0000000000..4ff92d2910 Binary files /dev/null and b/src/main/resources/img/pb.jpg differ diff --git a/src/main/resources/img/rs.jpg b/src/main/resources/img/rs.jpg new file mode 100644 index 0000000000..5049392ef7 Binary files /dev/null and b/src/main/resources/img/rs.jpg differ diff --git a/src/test/java/duke/Utils/CommandTest.java b/src/test/java/duke/Utils/CommandTest.java new file mode 100644 index 0000000000..b13e46b7c9 --- /dev/null +++ b/src/test/java/duke/Utils/CommandTest.java @@ -0,0 +1,89 @@ +package duke.utils; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.time.LocalDateTime; + +import org.junit.jupiter.api.Test; + +public class CommandTest { + public final String testCommand = "test"; + @Test + public void commandValidStringTest() { + String[] validString = { "/test 12345 6789", "/test []\\-=;':<>?." }; + String[] actualString = { "12345 6789", "[]\\-=;':<>?." }; + + for (int i = 0; i < validString.length; i++) { + assertEquals(Command.assertString(validString[i], testCommand), actualString[i]); + } + } + + @Test + public void commandInvalidStringTest() { + String[] invalidString = { "/test", "/test " }; + + for (String string : invalidString) { + assertThrows(InvalidArgumentException.class, () -> Command.assertString(string, testCommand)); + } + } + + @Test + public void commandValidIntegerTest() { + String[] validInteger = { "/test 99999999", "/test 123", "/test 0" , "/test -99999999" }; + int[] testInt = { 99999999, 123, 0, -99999999 }; + for (int i = 0; i < validInteger.length; i++) { + assertEquals(Command.assertInteger(validInteger[i], testCommand), testInt[i]); + } + } + + @Test + public void commandInvalidIntegerTest() { + String[] invalidInteger = { "/test", "/test 123 456", "/test 123.456", "/test 123]456", "/test asdgd qwe gew" }; + + for (String string : invalidInteger) { + assertThrows(InvalidArgumentException.class, () -> Command.assertInteger(string, testCommand)); + } + } + + @Test + public void commandValidDateTimeTest() { + String[] validDateTimeInput = { + "test 2022-09-07 12:34", + "test 1999-07-22 23:59", + "test 2040-12-31 00:00" + }; + + String[] validDateTimeString = { + "2022-09-07T12:34:00", + "1999-07-22T23:59:00", + "2040-12-31T00:00:00" + }; + + for (int i = 0; i < validDateTimeInput.length; i++) { + assertEquals( + Command.assertDateTime(validDateTimeInput[i], testCommand) + .isEqual(LocalDateTime.parse(validDateTimeString[i])), + true + ); + } + } + + @Test + public void commandInvalidDateTimeTest() { + String[] invalidDateTimeInput = { + "test 2022-09-07 1234", + "test 1999/07/22 23:59", + "test 00:00 2022-09-07", + "test 2022-13-01 00:00", + "test 2022-04-31 00:00", + "test 2022-05-32 00:00", + "test 2022-09-07 24:00", + "test 2022-09-07 12:60" + }; + + for (String string : invalidDateTimeInput) { + assertThrows(InvalidArgumentException.class, () -> Command.assertDateTime(string, testCommand)); + } + } +} diff --git a/text-ui-test/EXPECTED.TXT b/text-ui-test/EXPECTED.TXT deleted file mode 100644 index 657e74f6e7..0000000000 --- a/text-ui-test/EXPECTED.TXT +++ /dev/null @@ -1,7 +0,0 @@ -Hello from - ____ _ -| _ \ _ _| | _____ -| | | | | | | |/ / _ \ -| |_| | |_| | < __/ -|____/ \__,_|_|\_\___| - diff --git a/text-ui-test/input.txt b/text-ui-test/input.txt deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/text-ui-test/runtest.bat b/text-ui-test/runtest.bat deleted file mode 100644 index 0873744649..0000000000 --- a/text-ui-test/runtest.bat +++ /dev/null @@ -1,21 +0,0 @@ -@ECHO OFF - -REM create bin directory if it doesn't exist -if not exist ..\bin mkdir ..\bin - -REM delete output from previous run -if exist ACTUAL.TXT del ACTUAL.TXT - -REM compile the code into the bin folder -javac -cp ..\src\main\java -Xlint:none -d ..\bin ..\src\main\java\*.java -IF ERRORLEVEL 1 ( - echo ********** BUILD FAILURE ********** - exit /b 1 -) -REM no error here, errorlevel == 0 - -REM run the program, feed commands from input.txt file and redirect the output to the ACTUAL.TXT -java -classpath ..\bin Duke < input.txt > ACTUAL.TXT - -REM compare the output to the expected output -FC ACTUAL.TXT EXPECTED.TXT diff --git a/text-ui-test/runtest.sh b/text-ui-test/runtest.sh deleted file mode 100644 index c9ec870033..0000000000 --- a/text-ui-test/runtest.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash - -# create bin directory if it doesn't exist -if [ ! -d "../bin" ] -then - mkdir ../bin -fi - -# delete output from previous run -if [ -e "./ACTUAL.TXT" ] -then - rm ACTUAL.TXT -fi - -# compile the code into the bin folder, terminates if error occurred -if ! javac -cp ../src/main/java -Xlint:none -d ../bin ../src/main/java/*.java -then - echo "********** BUILD FAILURE **********" - exit 1 -fi - -# run the program, feed commands from input.txt file and redirect the output to the ACTUAL.TXT -java -classpath ../bin Duke < input.txt > ACTUAL.TXT - -# convert to UNIX format -cp EXPECTED.TXT EXPECTED-UNIX.TXT -dos2unix ACTUAL.TXT EXPECTED-UNIX.TXT - -# compare the output to the expected output -diff ACTUAL.TXT EXPECTED-UNIX.TXT -if [ $? -eq 0 ] -then - echo "Test result: PASSED" - exit 0 -else - echo "Test result: FAILED" - exit 1 -fi \ No newline at end of file