diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..097f9f98d9 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + diff --git a/.gitignore b/.gitignore index 2873e189e1..a189f150d4 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,9 @@ bin/ /text-ui-test/ACTUAL.TXT text-ui-test/EXPECTED-UNIX.TXT + +# Ignore Gradle project-specific cache directory +.gradle + +# Ignore Gradle build output directory +build diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000000..e0f15db2eb --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "java.configuration.updateBuildConfiguration": "automatic" +} \ No newline at end of file diff --git a/README.md b/README.md deleted file mode 100644 index 8715d4d915..0000000000 --- a/README.md +++ /dev/null @@ -1,24 +0,0 @@ -# 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 - ____ _ - | _ \ _ _| | _____ - | | | | | | | |/ / _ \ - | |_| | |_| | < __/ - |____/ \__,_|_|\_\___| - ``` diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..280746b523 --- /dev/null +++ b/build.gradle @@ -0,0 +1,65 @@ +plugins { + id 'java' + id 'application' + id 'checkstyle' + id 'org.openjfx.javafxplugin' version '0.0.10' + id 'com.github.johnrengelman.shadow' version '7.1.2' +} + +application { + mainClass.set("chatbot.ui.Launcher") +} + +checkstyle { + toolVersion = '10.2' +} + +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' + + // JavaFX 17.0.7 dependencies for macOS on ARM64 + implementation 'org.openjfx:javafx-base:17.0.7:mac-aarch64' + implementation 'org.openjfx:javafx-controls:17.0.7:mac-aarch64' + implementation 'org.openjfx:javafx-fxml:17.0.7:mac-aarch64' + implementation 'org.openjfx:javafx-graphics:17.0.7:mac-aarch64' + + // JavaFX 17.0.7 dependencies for Linux + implementation 'org.openjfx:javafx-base:17.0.7:linux' + implementation 'org.openjfx:javafx-controls:17.0.7:linux' + implementation 'org.openjfx:javafx-fxml:17.0.7:linux' + implementation 'org.openjfx:javafx-graphics:17.0.7:linux' + + // JavaFX 17.0.7 dependencies for Windows + implementation 'org.openjfx:javafx-base:17.0.7:win' + implementation 'org.openjfx:javafx-controls:17.0.7:win' + implementation 'org.openjfx:javafx-fxml:17.0.7:win' + implementation 'org.openjfx:javafx-graphics:17.0.7:win' +} + + +test { + useJUnitPlatform() + + testLogging { + events "passed", "skipped", "failed" + + showExceptions true + exceptionFormat "full" + showCauses true + showStackTraces true + showStandardStreams = false + } +} + +shadowJar { + archiveFileName = 'ChatBot.jar' +} + +repositories { + mavenCentral() +} + +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..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/data/chatbot.txt b/data/chatbot.txt new file mode 100644 index 0000000000..4f6e8851c1 --- /dev/null +++ b/data/chatbot.txt @@ -0,0 +1 @@ +T | 0 | dog diff --git a/docs/README.md b/docs/README.md index 8077118ebe..855af35973 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,29 +1,109 @@ -# User Guide +# ChatBot (Bobby Wasabi) # +Bobby Wasabi is your new best friend! He is a chatbot capable of **keeping track of all your deadlines, todos, and events!** Not only that with his somewhat **thorny personality**, he is sure to keep you on track to finishing all your tasks (or he will berate you!). It is a desktop app optimised via a Command Line Interface, together with a Graphical User Interface. -## Features +## Quick Start ## +1. Ensure you have Java 11 or above installed in your Computer. +2. Download the latest ChatBot.jar. +3. Copy the file to the folder you want to use as the home folder for your ChatBot +4. Open a command terminal, cd into the folder you put the jar file in, and use the java -jar ChatBot.jar command to run the application. A GUI should pop up! +5. Type in commands and press enter to execute! Here are some examples: + - list: Lists all current tasks + - todo Homework: adds a To-Do item onto your list named Homework + - mark 1: Marks the first item on your list as done -### Feature-ABC +## Features ## +> [NOTE] +> Words in UPPER_CASE need to be supplied by the user. -Description of the feature. +### Adding a To-Do: todo ### +Adds a To-Do to your list. -### Feature-XYZ +Format: todo NAME -Description of the feature. +Examples: +- todo Submit CS2103T IP +- todo Laundry -## Usage +### Adding a Deadline: deadline ### +Adds a deadline to your list. -### `Keyword` - Describe action +Format: deadline NAME /by DATE_AND_TIME -Describe the action and its outcome. +- Date must be in format yyyy-MM-dd HHmm +Examples: +- deadline CS2103T IP 2023-09-22 2359 +- deadline IPPT 2023-12-26 2359 -Example of usage: +### Adding an Event: event ### +Adds an event to your list. -`keyword (optional arguments)` +Format: event NAME /from START_TIME /to END_TIME +- START_TIME and END_TIME must be in format yyyy-MM-dd HHmm -Expected outcome: +Examples: +- event Birthday Party /from 2023-09-20 1400 /to 2023-09-20 2300 +- event Orientation Camp /from 2023-09-30 1200 /to 2023-10-02 2200 -Description of the outcome. +### Listing items on the list: list ### +List all current items on the list. Displays whether they have been done or not. -``` -expected output -``` +Format: list + +### Marking an item as done: mark ### +Marks an item on the list as done. + +Format: mark INDEX +- INDEX must be a positive non-zero integer, e.g. 1, 2, 3 +- INDEX must also be a valid index on the list. + +Examples: +- mark 1 + +### Unmark an item as undone: unmark ### +Unmarks an item as undone. + +Format: unmark INDEX +- INDEX must be a positive non-zero integer, e.g. 1, 2, 3 +- INDEX must also be a valid index on the list. + +Examples: +- unmark 1 + +### Delete an item off the list: delete ### +Deletes an item off the list. + +Format: delete INDEX +- INDEX must be a positive non-zero integer, e.g. 1, 2, 3 +- INDEX must also be a valid index on the list. + +Example: +- delete 1 + +### Find an item on the list: find ### +Finds all items on the list containing the given prompts. + +Format: find PROMPT +- Prompt is a string containing any character. +- Returns nothing if nothing is found. + +Example: +- find Birthday Party +- find CS2103T-IP-Assignment + +### List all duplicates found: listduplicate ### +Lists all entries in the list with duplicate names. + +Format: listduplicate + +### Delete all duplicates found: deleteduplicate ### +Deletes duplicates found, and leaves the first entry behind. + +Format: deleteduplicates + +### Exiting the chatbot: bye ### +Exits the chat. + +Format: bye + +### Saving data ### +Data is automatically saved on a .txt file whenever queries are made. diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..e6c3d157dd 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..7f93135c49 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..d11cdd907d --- /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-8.3-all.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000000..0adc8e1a53 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/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##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && 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..93e3f59f13 --- /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/settings.gradle b/settings.gradle new file mode 100644 index 0000000000..1bffb74d31 --- /dev/null +++ b/settings.gradle @@ -0,0 +1,8 @@ +/* + * This file was generated by the Gradle 'init' task. + * + * The settings file is used to specify which projects to include in your build. + * For more detailed information on multi-project builds, please refer to https://docs.gradle.org/8.3/userguide/building_swift_projects.html in the Gradle documentation. + */ + +rootProject.name = "ip" 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/chatbot/ChatBot.java b/src/main/java/chatbot/ChatBot.java new file mode 100644 index 0000000000..d6b1d8473e --- /dev/null +++ b/src/main/java/chatbot/ChatBot.java @@ -0,0 +1,53 @@ +package chatbot; + +import chatbot.commands.Command; +import chatbot.exceptions.ChatBotException; +import chatbot.parser.Parser; +import chatbot.storage.Storage; +import chatbot.task.TaskList; +import chatbot.ui.Printer; +/** + * A chat bot that can be renamed, and responds to inputs from users + * + * @author Owen Yeo + */ +public class ChatBot { + + private Storage storage; + private TaskList tasks; + private Printer ui; + + /** + * Constructs a ChatBot instance. + */ + public ChatBot() { + ui = new Printer(); + storage = new Storage("data/chatbot.txt"); + try { + tasks = new TaskList(storage.load()); + } catch (ChatBotException e) { + ui.showError(e); + tasks = new TaskList(); + } + } + + /** + * Returns the introduction of the chat bot. + * + * @return String of the introduction + */ + public String showIntro() { + return ui.intro(); + } + + /** + * Responds to user input. + * + * @param input User input + * @return String depending on user iput + */ + public String getResponse(String input) { + Command c = Parser.parse(input); + return c.execute(tasks, storage, ui); + } +} diff --git a/src/main/java/chatbot/Main.java b/src/main/java/chatbot/Main.java new file mode 100644 index 0000000000..a99786d580 --- /dev/null +++ b/src/main/java/chatbot/Main.java @@ -0,0 +1,37 @@ +package chatbot; + +import chatbot.ui.MainWindow; + +import java.io.IOException; +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Scene; +import javafx.scene.layout.AnchorPane; +import javafx.stage.Stage; + +/** + * A GUI for ChatBot using FXML. + */ +public class Main extends Application { + + private ChatBot chatBot; + + /** + * {@inheritDoc} + */ + @Override + public void start(Stage stage) { + + chatBot = new ChatBot(); + try { + FXMLLoader fxmlLoader = new FXMLLoader(Main.class.getResource("/view/MainWindow.fxml")); + AnchorPane ap = fxmlLoader.load(); + Scene scene = new Scene(ap); + stage.setScene(scene); + fxmlLoader.getController().setChatBot(chatBot); + stage.show(); + } catch (IOException e) { + e.printStackTrace(); + } + } +} diff --git a/src/main/java/chatbot/commands/AddDeadline.java b/src/main/java/chatbot/commands/AddDeadline.java new file mode 100644 index 0000000000..549ce1419d --- /dev/null +++ b/src/main/java/chatbot/commands/AddDeadline.java @@ -0,0 +1,52 @@ +package chatbot.commands; + +import chatbot.exceptions.InvalidDescriptionException; +import chatbot.storage.Storage; +import chatbot.task.TaskList; +import chatbot.task.TaskType; +import chatbot.ui.Printer; + +/** + * Adds a deadline task to the TaskList + * + * @author Owen Yeo + */ +public class AddDeadline extends Command { + + /** + * {@inheritDoc} + * @param input + * @param commandType + */ + public AddDeadline(String input, CommandType commandType) { + super(input, commandType); + } + + /** + * {@inheritDoc} + * + * Adds a Deadline to the TaskList of the chatbot and saves it. + * Prints a message on the UI. + */ + @Override + public String execute(TaskList tasks, Storage storage, Printer ui) { + try { + tasks.addTask(input, TaskType.DEADLINE); + storage.saveTasks(tasks); + + String[] output = new String[5]; + + if (tasks.detectDuplicate(tasks.getTask(tasks.getLength()).getLabel())) { + output[0] = "You already have this task in your list. Stop adding duplicates."; + } + + output[1] = "What? You ain't finishing it. Added: "; + output[2] = tasks.getTask(tasks.getLength()).toString(); + output[3] = "Now you have an overwhelming " + tasks.getLength() + " things to do."; + + return ui.print(output); + } catch (InvalidDescriptionException e) { + return ui.showError(e); + } + } +} diff --git a/src/main/java/chatbot/commands/AddEvent.java b/src/main/java/chatbot/commands/AddEvent.java new file mode 100644 index 0000000000..78304b3978 --- /dev/null +++ b/src/main/java/chatbot/commands/AddEvent.java @@ -0,0 +1,47 @@ +package chatbot.commands; + +import chatbot.exceptions.InvalidDescriptionException; +import chatbot.storage.Storage; +import chatbot.task.TaskList; +import chatbot.task.TaskType; +import chatbot.ui.Printer; + +/** + * Add an event task to the TaskList + * + * @author Owen Yeo + */ +public class AddEvent extends Command { + + public AddEvent(String input, CommandType commandType) { + super(input, commandType); + } + + /** + * {@inheritDoc} + * + * Adds an Event to the TaskList of the chatbot and saves it. + * Prints a message on the UI. + */ + @Override + public String execute(TaskList tasks, Storage storage, Printer ui) { + try { + tasks.addTask(input, TaskType.EVENT); + storage.saveTasks(tasks); + + String[] output = new String[5]; + + if (tasks.detectDuplicate(tasks.getTask(tasks.getLength()).getLabel())) { + output[0] = "You already have this task in your list. Stop adding duplicates."; + } + + output[1] = "What? You ain't finishing it. Added: "; + output[2] = tasks.getTask(tasks.getLength()).toString(); + output[3] = "Now you have an overwhelming " + tasks.getLength() + " things to do."; + + return ui.print(output); + } catch (InvalidDescriptionException e) { + return ui.showError(e); + } + } +} diff --git a/src/main/java/chatbot/commands/AddToDo.java b/src/main/java/chatbot/commands/AddToDo.java new file mode 100644 index 0000000000..2df5c80b20 --- /dev/null +++ b/src/main/java/chatbot/commands/AddToDo.java @@ -0,0 +1,47 @@ +package chatbot.commands; + +import chatbot.exceptions.InvalidDescriptionException; +import chatbot.storage.Storage; +import chatbot.task.TaskList; +import chatbot.task.TaskType; +import chatbot.ui.Printer; + +/** + * Adds a To Do task to the TaskList + * + * @author Owen Yeo + */ +public class AddToDo extends Command { + + public AddToDo(String input, CommandType commandType) { + super(input, commandType); + } + + /** + * {@inheritDoc} + * + * Adds a todo to the TaskList of the chatbot and saves it. + * Prints a message on the UI. + */ + @Override + public String execute(TaskList tasks, Storage storage, Printer ui) { + try { + tasks.addTask(input, TaskType.TODO); + storage.saveTasks(tasks); + + String[] output = new String[5]; + + if (tasks.detectDuplicate(tasks.getTask(tasks.getLength()).getLabel())) { + output[0] = "You already have this task in your list. Stop adding duplicates."; + } + + output[1] = "What? You ain't finishing it. Added: "; + output[2] = tasks.getTask(tasks.getLength()).toString(); + output[3] = "Now you have an overwhelming " + tasks.getLength() + " things to do."; + + return ui.print(output); + } catch (InvalidDescriptionException e) { + return ui.showError(e); + } + } +} diff --git a/src/main/java/chatbot/commands/Bye.java b/src/main/java/chatbot/commands/Bye.java new file mode 100644 index 0000000000..3e80fb1ba8 --- /dev/null +++ b/src/main/java/chatbot/commands/Bye.java @@ -0,0 +1,35 @@ +package chatbot.commands; + +import chatbot.storage.Storage; +import chatbot.task.TaskList; +import chatbot.ui.Printer; + +/** + * Command that exits the chatbot and forces it close. + */ +public class Bye extends Command { + + public Bye(String input, CommandType commandType) { + super(input, commandType); + } + + /** + * {@inheritDoc} + * + * Asks UI to print a goodbye message. + */ + @Override + public String execute(TaskList tasks, Storage storage, Printer ui) { + return ui.bye(); + } + + /** + * {@inheritDoc} + * + * @return true. + */ + @Override + public boolean isExit() { + return true; + } +} diff --git a/src/main/java/chatbot/commands/Command.java b/src/main/java/chatbot/commands/Command.java new file mode 100644 index 0000000000..9c7dde8abc --- /dev/null +++ b/src/main/java/chatbot/commands/Command.java @@ -0,0 +1,56 @@ +package chatbot.commands; + +import chatbot.storage.Storage; +import chatbot.task.TaskList; +import chatbot.ui.Printer; + +/** + * Abstract class representing a command. + * + * @author Owen Yeo + */ +public abstract class Command { + + protected final String input; + protected final CommandType commandType; + + /** + * Constructs a Command instance with a given type and input. + * + * @param input String containing task label and other info. + * @param commandType type of command instance + */ + public Command(String input, CommandType commandType) { + this.input = input; + this.commandType = commandType; + } + + /** + * Modifies the TaskList, Storage, and UI of the ChatBot. + * + * @param tasks TaskList + * @param storage Storage + * @param printer Printer + */ + public String execute(TaskList tasks, Storage storage, Printer printer) { + return printer.intro(); + } + + /** + * Checks if the current command will cause an exit. + * + * @return false + */ + public boolean isExit() { + return false; + } + + /** + * Getter for commandType. Mainly used for testing. + * + * @return CommandType of the command. + */ + public CommandType getType() { + return this.commandType; + } +} diff --git a/src/main/java/chatbot/commands/CommandType.java b/src/main/java/chatbot/commands/CommandType.java new file mode 100644 index 0000000000..830318b670 --- /dev/null +++ b/src/main/java/chatbot/commands/CommandType.java @@ -0,0 +1,47 @@ +package chatbot.commands; + +/** + * enum that represents the different command types. + * + * @author Owen Yeo + */ +public enum CommandType { + BYE("bye"), + DISPLAY_LIST("list"), + MARK("mark"), + UNMARK("unmark"), + ADD_TODO("todo"), + ADD_DEADLINE("deadline"), + ADD_EVENT("event"), + DELETE("delete"), + FIND("find"), + SHOWERROR(""), + LIST_DUPLICATE("listduplicate"), + DELETE_DUPLICATE("deleteduplicate"); + + private final String input; + + private CommandType(String input) { + this.input = input; + } + + /** + * Parses the input and returns the appropriate command if the input is + * valid. + * + * @param input User's input + * @return Command that tells what the chatbot should do. + */ + public static CommandType parseInput(String input) { + String[] parts = input.split(" ", 2); + + assert parts.length > 0 : "Input should not be empty"; + + for (CommandType commandType: CommandType.values()) { + if (commandType.input.equals(parts[0])) { + return commandType; + } + } + return SHOWERROR; + } +} diff --git a/src/main/java/chatbot/commands/DeleteDuplicates.java b/src/main/java/chatbot/commands/DeleteDuplicates.java new file mode 100644 index 0000000000..d721bcee7a --- /dev/null +++ b/src/main/java/chatbot/commands/DeleteDuplicates.java @@ -0,0 +1,33 @@ +package chatbot.commands; + +import chatbot.storage.Storage; +import chatbot.task.TaskList; +import chatbot.ui.Printer; + +/** + * Deletes duplicate tasks from the list. + */ +public class DeleteDuplicates extends Command { + + /** + * Constructs a DeleteDuplicates instance with a given type and input. + * @param input String containing task label and other info. + * @param commandType type of command instance + */ + public DeleteDuplicates(String input, CommandType commandType) { + super(input, commandType); + } + + /** + * {@inheritDoc} + */ + @Override + public String execute(TaskList tasks, Storage storage, Printer ui) { + try { + tasks.deleteDuplicates(); + return ui.print(new String[] {"Duplicates deleted."}); + } catch (Exception e) { + return ui.showError(e); + } + } +} diff --git a/src/main/java/chatbot/commands/DeleteItem.java b/src/main/java/chatbot/commands/DeleteItem.java new file mode 100644 index 0000000000..73371edeb3 --- /dev/null +++ b/src/main/java/chatbot/commands/DeleteItem.java @@ -0,0 +1,50 @@ +package chatbot.commands; + +import chatbot.exceptions.InvalidIndexException; +import chatbot.storage.Storage; +import chatbot.task.Task; +import chatbot.task.TaskList; +import chatbot.ui.Printer; + +/** + * Command that deletes an item from the TaskList, and prints a message. + */ +public class DeleteItem extends Command { + + public DeleteItem(String input, CommandType commandType) { + super(input, commandType); + } + + /** + * {@inheritDoc} + * + * Deletes item from the TaskList and saves it. + * Prints a message on the UI. + * + * @throws InvalidIndexEception Thrown when no tasks matches the index. + */ + @Override + public String execute(TaskList tasks, Storage storage, Printer ui) + throws InvalidIndexException { + try { + int index = Integer.parseInt(input); + + assert index < tasks.getLength() : "index cannot be greater than length of tasklist"; + assert index > 0 : "index cannot be less than 1"; + + Task deletedTask = tasks.getTask(index); + tasks.delete(Integer.parseInt(input)); + storage.saveTasks(tasks); + + return ui.print(new String[] {"I knew you couldn't finish it. Or maybe you did. I don't care. Deleted:", + deletedTask.toString(), + "Now you have an overwhelming " + (tasks.getLength()) + + " things to do" + }); + } catch (NumberFormatException e) { + return ui.showError(new InvalidIndexException("Are you stupid? That's not a number.")); + } catch (IndexOutOfBoundsException e) { + return ui.showError(new InvalidIndexException("Are you stupid? That's not a number on the list.")); + } + } +} diff --git a/src/main/java/chatbot/commands/DisplayList.java b/src/main/java/chatbot/commands/DisplayList.java new file mode 100644 index 0000000000..4ba38f8b86 --- /dev/null +++ b/src/main/java/chatbot/commands/DisplayList.java @@ -0,0 +1,34 @@ +package chatbot.commands; + +import chatbot.storage.Storage; +import chatbot.task.TaskList; +import chatbot.ui.Printer; + +/** + * Displays the existing list when executed + * + * @author Owen Yeo + */ +public class DisplayList extends Command{ + + public DisplayList(String input, CommandType commandType) { + super(input, commandType); + } + + /** + * {@inheritDoc} + * + * Displays the current list on the UI when executed. + */ + @Override + public String execute(TaskList tasks, Storage storage, Printer ui) { + String[] taskStrings = new String[100]; + + for (int i = 1; i < tasks.getLength() + 1; i++) { + String listString = (i) + ". " + tasks.getTask(i).toString(); + taskStrings[i - 1] = listString; + } + + return ui.print(taskStrings); + } +} diff --git a/src/main/java/chatbot/commands/FindTask.java b/src/main/java/chatbot/commands/FindTask.java new file mode 100644 index 0000000000..0020225f56 --- /dev/null +++ b/src/main/java/chatbot/commands/FindTask.java @@ -0,0 +1,38 @@ +package chatbot.commands; + + +import chatbot.storage.Storage; +import chatbot.task.TaskList; +import chatbot.ui.Printer; + +/** + * Finds the items in the list that match the query. + */ +public class FindTask extends Command { + + public FindTask(String input, CommandType commandType) { + super(input, commandType); + } + + /** + * {@inheritDoc} + * \ + * Finds the tasks that contain the words found in the input. + */ + @Override + public String execute(TaskList tasks, Storage storage, Printer ui) { + String[] validStrings = new String[100]; + validStrings[0] = "Here are items that match your search:"; + + int index = 1; + + for (int i = 1; i < tasks.getLength() + 1; i++) { + String taskString = tasks.getTask(i).toString(); + if (taskString.indexOf(input) != -1) { + validStrings[index] = index + ". " + taskString; + index++; + } + } + return ui.print(validStrings); + } +} diff --git a/src/main/java/chatbot/commands/ListDuplicates.java b/src/main/java/chatbot/commands/ListDuplicates.java new file mode 100644 index 0000000000..3899d67782 --- /dev/null +++ b/src/main/java/chatbot/commands/ListDuplicates.java @@ -0,0 +1,46 @@ +package chatbot.commands; + +import chatbot.task.Task; +import chatbot.task.TaskList; + +import java.util.ArrayList; + +import chatbot.storage.Storage; +import chatbot.ui.Printer; + +/** + * Lists the duplicate tasks in the list. + */ +public class ListDuplicates extends Command { + + /** + * Constructor for a ListDuplicates instance. + * + * @param input String containing task label and other info. + * @param commandType type of command instance + */ + public ListDuplicates(String input, CommandType commandType) { + super(input, commandType); + } + + /** + * {@inheritDoc} + */ + @Override + public String execute(TaskList tasks, Storage storage, Printer ui) { + try { + String[] duplicateTaskStrings = new String[100]; + + duplicateTaskStrings[0] = "Here are the duplicate tasks:"; + ArrayList duplicateTasks = tasks.getDuplicateTasks(); + + for (int i = 1; i < duplicateTasks.size() + 1; i++) { + String listString = duplicateTasks.get(i - 1).toString(); + duplicateTaskStrings[i] = listString; + } + return ui.print(duplicateTaskStrings); + } catch (Exception e) { + return ui.showError(e); + } + } +} diff --git a/src/main/java/chatbot/commands/MarkItem.java b/src/main/java/chatbot/commands/MarkItem.java new file mode 100644 index 0000000000..0016149475 --- /dev/null +++ b/src/main/java/chatbot/commands/MarkItem.java @@ -0,0 +1,49 @@ +package chatbot.commands; + +import chatbot.exceptions.InvalidIndexException; +import chatbot.storage.Storage; +import chatbot.task.TaskList; +import chatbot.ui.Printer; + +/** + * Marks item as completed in the list + * + * @author Owen Yeo + */ +public class MarkItem extends Command { + + public MarkItem(String input, CommandType commandType) { + super(input, commandType); + } + + /** + * {@inheritDoc} + * + * Marks an item on the tasklist as done, and prints a message on the UI. + * Saves the change on the text file. + * + * @throws InvalidIndexEception Thrown when no tasks matches the index. + */ + @Override + public String execute(TaskList tasks, Storage storage, Printer ui) + throws InvalidIndexException { + try { + int index = Integer.parseInt(input); + + assert index < tasks.getLength() : "index cannot be greater than length of tasklist"; + assert index > 0 : "index cannot be less than 1"; + + tasks.mark(index); + storage.saveTasks(tasks); + + return ui.print(new String[] { + "Impossible! You must have cheated. Horrible.", + tasks.getTask(index).toString() + }); + } catch (NumberFormatException e) { + return ui.showError(new InvalidIndexException("Are you stupid? That's not a number.")); + } catch (IndexOutOfBoundsException e) { + return ui.showError(new InvalidIndexException("Are you stupid? That's not a number on the list.")); + } + } +} diff --git a/src/main/java/chatbot/commands/ShowError.java b/src/main/java/chatbot/commands/ShowError.java new file mode 100644 index 0000000000..7d5b04de06 --- /dev/null +++ b/src/main/java/chatbot/commands/ShowError.java @@ -0,0 +1,38 @@ +package chatbot.commands; + +import chatbot.exceptions.ChatBotException; +import chatbot.exceptions.InvalidIndexException; +import chatbot.storage.Storage; +import chatbot.task.TaskList; +import chatbot.ui.Printer; + +/** + * Displays the error message when executed. + */ +public class ShowError extends Command { + + private ChatBotException chatBotException; + + /** + * {@inheritDoc} + * + * Displays the error when executed. + * + * @param input User input + * @param commandType Type of command + * @param exception Exception to be displayed + */ + public ShowError(String input, CommandType commandType, ChatBotException exception) { + super(input, commandType); + this.chatBotException = exception; + } + + /** + * {@inheritDoc} + */ + @Override + public String execute(TaskList tasks, Storage storage, Printer ui) + throws InvalidIndexException { + return ui.showError(this.chatBotException); + } +} diff --git a/src/main/java/chatbot/commands/UnmarkItem.java b/src/main/java/chatbot/commands/UnmarkItem.java new file mode 100644 index 0000000000..ff723a35b4 --- /dev/null +++ b/src/main/java/chatbot/commands/UnmarkItem.java @@ -0,0 +1,49 @@ +package chatbot.commands; + +import chatbot.exceptions.InvalidIndexException; +import chatbot.storage.Storage; +import chatbot.task.TaskList; +import chatbot.ui.Printer; + +/** + * Unmarks a completed item as undone. + * + * @author Owen Yeo + */ +public class UnmarkItem extends Command { + + public UnmarkItem(String input, CommandType commandType) { + super(input, commandType); + } + + /** + * {@inheritDoc} + * + * Unmarks a task on the TaskList as undone, and prints a message. + * Saves the change on a data file. + * + * @throws InvalidIndexEception Thrown when no tasks matches the index. + */ + @Override + public String execute(TaskList tasks, Storage storage, Printer ui) + throws InvalidIndexException { + try { + int index = Integer.parseInt(input); + + assert index < tasks.getLength() : "index cannot be greater than length of tasklist"; + assert index > 0 : "index cannot be less than 1"; + + tasks.unmark(index); + + storage.saveTasks(tasks); + return ui.print(new String[] { + "You incompetent child. I've unmarked the task. Please get it together.", + tasks.getTask(index).toString() + }); + } catch (NumberFormatException e) { + return ui.showError(new InvalidIndexException("Are you stupid? That's not a number.")); + } catch (IndexOutOfBoundsException e) { + return ui.showError(new InvalidIndexException("Are you stupid? That's not a number on the list.")); + } + } +} diff --git a/src/main/java/chatbot/exceptions/ChatBotException.java b/src/main/java/chatbot/exceptions/ChatBotException.java new file mode 100644 index 0000000000..453b06ed52 --- /dev/null +++ b/src/main/java/chatbot/exceptions/ChatBotException.java @@ -0,0 +1,14 @@ +package chatbot.exceptions; + +/** + * Class representing exceptions thrown by the chatbot. + * + * @author Owen Yeo + */ +public class ChatBotException extends RuntimeException { + + public ChatBotException(String e) { + super(e); + } + +} diff --git a/src/main/java/chatbot/exceptions/InvalidCommandException.java b/src/main/java/chatbot/exceptions/InvalidCommandException.java new file mode 100644 index 0000000000..478298be60 --- /dev/null +++ b/src/main/java/chatbot/exceptions/InvalidCommandException.java @@ -0,0 +1,13 @@ +package chatbot.exceptions; +/** + * Exception that is thrown when an invalid command is keyed into the chatbot. + * + * @author Owen Yeo + */ +public class InvalidCommandException extends ChatBotException { + + public InvalidCommandException(String e) { + super(e); + } + +} diff --git a/src/main/java/chatbot/exceptions/InvalidDescriptionException.java b/src/main/java/chatbot/exceptions/InvalidDescriptionException.java new file mode 100644 index 0000000000..aafa8ca82d --- /dev/null +++ b/src/main/java/chatbot/exceptions/InvalidDescriptionException.java @@ -0,0 +1,14 @@ +package chatbot.exceptions; + +/** + * Exception that is thrown when a command is correct but the description + * is wrong. + * + * @author Owen Yeo + */ +public class InvalidDescriptionException extends ChatBotException { + + public InvalidDescriptionException(String e) { + super(e); + } +} diff --git a/src/main/java/chatbot/exceptions/InvalidIndexException.java b/src/main/java/chatbot/exceptions/InvalidIndexException.java new file mode 100644 index 0000000000..3d0332b9fb --- /dev/null +++ b/src/main/java/chatbot/exceptions/InvalidIndexException.java @@ -0,0 +1,13 @@ +package chatbot.exceptions; + +/** + * Exception thrown when the index given for mark, unmark, or delete is wrong. + * + * @author Owen Yeo + */ +public class InvalidIndexException extends ChatBotException { + + public InvalidIndexException(String e) { + super(e); + } +} diff --git a/src/main/java/chatbot/exceptions/SaveFileNotFound.java b/src/main/java/chatbot/exceptions/SaveFileNotFound.java new file mode 100644 index 0000000000..8a9458d2d6 --- /dev/null +++ b/src/main/java/chatbot/exceptions/SaveFileNotFound.java @@ -0,0 +1,12 @@ +package chatbot.exceptions; + +/** + * Exception that is thrown when the save file is not found. + */ +public class SaveFileNotFound extends ChatBotException { + + public SaveFileNotFound(String e) { + super(e); + } + +} diff --git a/src/main/java/chatbot/parser/Parser.java b/src/main/java/chatbot/parser/Parser.java new file mode 100644 index 0000000000..06f2b32dbf --- /dev/null +++ b/src/main/java/chatbot/parser/Parser.java @@ -0,0 +1,85 @@ +package chatbot.parser; + +import chatbot.commands.AddDeadline; +import chatbot.commands.AddEvent; +import chatbot.commands.AddToDo; +import chatbot.commands.Bye; +import chatbot.commands.Command; +import chatbot.commands.CommandType; +import chatbot.commands.DeleteDuplicates; +import chatbot.commands.DeleteItem; +import chatbot.commands.DisplayList; +import chatbot.commands.FindTask; +import chatbot.commands.ListDuplicates; +import chatbot.commands.MarkItem; +import chatbot.commands.ShowError; +import chatbot.commands.UnmarkItem; +import chatbot.exceptions.InvalidCommandException; +import chatbot.exceptions.InvalidDescriptionException; +import chatbot.exceptions.InvalidIndexException; + +/** + * Parser that parses the inputs from the user and inteprets it. + * + * @author Owen Yeo + */ +public class Parser { + + /** + * Parses the input from the user and outputs a command for + * the chatbot to execute. + * + * @param input String input from user + * @return Command command depending on input. + * @throws InvalidDescriptionException Exception thrown when an invalid command description is passed. + * @throws InvalidCommandException Exception thrown when an invalid command is passed + * @throws InvalidIndexException Exception thrown when an invalid index is passed. + */ + public static Command parse(String input) throws + InvalidDescriptionException, InvalidCommandException, InvalidIndexException { + //Split the input so that we can read command and their description (if any). + String[] inputStrings = input.split(" ", 2); + assert inputStrings.length > 0 : "Input should not be empty"; + + CommandType command = CommandType.parseInput(inputStrings[0]); + + switch(command) { + case BYE: + return new Bye("", CommandType.BYE); + + case DISPLAY_LIST: + return new DisplayList("", CommandType.DISPLAY_LIST); + + case MARK: + return new MarkItem(inputStrings[1], CommandType.MARK); + + case UNMARK: + return new UnmarkItem(inputStrings[1], CommandType.UNMARK); + + case ADD_TODO: + return new AddToDo(inputStrings[1], CommandType.ADD_TODO); + + case ADD_DEADLINE: + return new AddDeadline(inputStrings[1], CommandType.ADD_DEADLINE); + + case ADD_EVENT: + return new AddEvent(inputStrings[1], CommandType.ADD_EVENT); + + case DELETE: + return new DeleteItem(inputStrings[1], CommandType.DELETE); + + case FIND: + return new FindTask(inputStrings[1], CommandType.FIND); + + case LIST_DUPLICATE: + return new ListDuplicates(input, CommandType.LIST_DUPLICATE); + + case DELETE_DUPLICATE: + return new DeleteDuplicates(input, CommandType.DELETE_DUPLICATE); + + default: + return new ShowError("", CommandType.SHOWERROR, + new InvalidCommandException("Don't be stupid, speak english.")); + } + } +} diff --git a/src/main/java/chatbot/storage/Storage.java b/src/main/java/chatbot/storage/Storage.java new file mode 100644 index 0000000000..0fe9792f38 --- /dev/null +++ b/src/main/java/chatbot/storage/Storage.java @@ -0,0 +1,116 @@ +package chatbot.storage; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; + +import chatbot.exceptions.SaveFileNotFound; +import chatbot.task.Deadline; +import chatbot.task.Event; +import chatbot.task.Task; +import chatbot.task.TaskList; +import chatbot.task.TaskType; +import chatbot.task.ToDo; + +/** + * Storage class that handles storing and loading saved lists. + * + * @author Owen Yeo + */ +public class Storage { + private String path; + + public Storage(String path) { + this.path = path; + File file = new File(path); + + if (!file.exists()) { + try { + file.getParentFile().mkdirs(); + FileWriter writer = new FileWriter(file); + writer.close(); + } catch (IOException e) { + System.out.println("Error creating file:" + e.getMessage()); + } + } + } + + /** + * Saves tasks into a text file. + * + * @param tasks TaskList + */ + public void saveTasks(TaskList tasks) { + try { + BufferedWriter bw = new BufferedWriter(new FileWriter( + path, false)); + + for (int i = 1; i < tasks.getLength() + 1; i++) { + bw.write(tasks.getTask(i).toSaveString()); + bw.newLine(); + } + bw.close(); + + } catch (IOException e) { + System.out.println("Error writing file:" + e.getMessage()); + } + } + + /** + * Loads the existing list found on the storage file into an ArrayList. + * + * @return ArrayList containing all the tasks parsed from the file. + */ + public ArrayList load() { + try { + ArrayList loadedList = new ArrayList<>(); + File file = new File(path); + + if (file.exists()) { + BufferedReader reader = new BufferedReader(new FileReader(file)); + String line; + while ((line = reader.readLine()) != null) { + String[] parts = line.split("\\|"); + TaskType taskType = TaskType.parseInput(parts[0].trim()); + switch (taskType) { + + case TODO: + loadedList.add(new ToDo(parts[2].trim())); + if (Integer.parseInt(parts[1].trim()) == 1) { + loadedList.get(loadedList.size() - 1).done(); + } + break; + + case DEADLINE: + loadedList.add(new Deadline(parts[2].trim(), parts[3].trim())); + if (Integer.parseInt(parts[1].trim()) == 1) { + Task task = loadedList.get(loadedList.size() - 1); + task.done(); + } + break; + + case EVENT: + loadedList.add(new Event(parts[2].trim(), parts[3].trim(), parts[4].trim())); + if (Integer.parseInt(parts[1].trim()) == 1) { + loadedList.get(loadedList.size() - 1).done(); + } + break; + + default: + break; + } + } + reader.close(); + + return loadedList; + } + } catch (IOException e) { + throw new SaveFileNotFound("You forgot your file path, idiot."); + } + return null; + } +} diff --git a/src/main/java/chatbot/task/Deadline.java b/src/main/java/chatbot/task/Deadline.java new file mode 100644 index 0000000000..e410be19a0 --- /dev/null +++ b/src/main/java/chatbot/task/Deadline.java @@ -0,0 +1,49 @@ +package chatbot.task; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Deadline class that inherits from Task. + * + * @author Owen Yeo + */ +public class Deadline extends Task { + + private LocalDateTime deadline; + + private String originalString; + + /** + * Constructor for a deadline object. + * + * @param label Descriptor for the task with deadline + * @param deadline String representing deadline + */ + public Deadline(String label, String deadline) { + super(label); + + assert deadline.length() > 0 : "Deadline cannot be empty"; + + this.deadline = LocalDateTime.parse(deadline, DateTimeFormatter + .ofPattern("yyyy-MM-dd HHmm")); + this.originalString = deadline; + } + + /** + * {@inheritDoc} + */ + @Override + public String toSaveString() { + return "D " + super.toSaveString() + " | " + originalString; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "[D]" + super.toString() + " (by: " + deadline + .format(DateTimeFormatter.ofPattern("MMM dd YYYY ha")) + ")"; + } +} diff --git a/src/main/java/chatbot/task/Event.java b/src/main/java/chatbot/task/Event.java new file mode 100644 index 0000000000..3f558574e5 --- /dev/null +++ b/src/main/java/chatbot/task/Event.java @@ -0,0 +1,57 @@ +package chatbot.task; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +/** + * Event class that inherits from Task. + * + * + * @author Owen Yeo + */ +public class Event extends Task { + private LocalDateTime from; + private LocalDateTime to; + private String fromString; + private String toString; + + /** + * Constructor for an event object. + * + * @param label Descriptor for the event + * @param from Start time + * @param to End time + */ + public Event(String label, String from, String to) { + super(label); + + assert from.length() > 0 : "From time cannot be empty"; + assert to.length() > 0 : "To time cannot be empty"; + + this.from = LocalDateTime.parse(from, DateTimeFormatter + .ofPattern("yyyy-MM-dd HHmm")); + this.fromString = from; + this.to = LocalDateTime.parse(to, DateTimeFormatter + .ofPattern("yyyy-MM-dd HHmm")); + this.toString = to; + } + + /** + * {@inheritDoc} + */ + @Override + public String toSaveString() { + return "E " + super.toSaveString() + " | " + fromString + " | " + + toString; + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "[E]" + super.toString() + " (from: " + from + .format(DateTimeFormatter.ofPattern("MMM dd YYYY ha")) + " | to: " + to + .format(DateTimeFormatter.ofPattern("MMM dd YYYY ha")) + ")"; + } +} diff --git a/src/main/java/chatbot/task/Task.java b/src/main/java/chatbot/task/Task.java new file mode 100644 index 0000000000..325edbf402 --- /dev/null +++ b/src/main/java/chatbot/task/Task.java @@ -0,0 +1,66 @@ +package chatbot.task; + +/** + * Abstract class representing a task object. + * + * @author Owen Yeo + * @version Level-7 + */ +public abstract class Task { + private String label; + private boolean isDone; + + /** + * Constructor for a task object + * + * @param label + */ + Task(String label) { + this.label = label; + this.isDone = false; + } + + /** + * sets isDone to true. + */ + public void done() { + isDone = true; + } + + /** + * sets isDone to false. + */ + public void undone() { + isDone = false; + } + + /** + * Returns a string to be saved in a file, representing a task. + * + * @return String representing a task. + */ + public String toSaveString() { + return "| " + (isDone ? 1 : 0) + " | " + label; + } + + /** + * Getter for label. + * @return String representing label. + */ + public String getLabel() { + return label; + } + + /** + * {@inheritDoc} + * + * Represents whether a task has been done or not. + */ + @Override + public String toString() { + if (isDone) { + return "[X] " + label; + } + return "[ ] " + label; + } +} diff --git a/src/main/java/chatbot/task/TaskList.java b/src/main/java/chatbot/task/TaskList.java new file mode 100644 index 0000000000..7dae9a5eea --- /dev/null +++ b/src/main/java/chatbot/task/TaskList.java @@ -0,0 +1,182 @@ +package chatbot.task; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Set; + +import chatbot.exceptions.InvalidDescriptionException; +import chatbot.exceptions.InvalidIndexException; + +/** + * Representation of a list that takes in tasks, + * and is able to modify their states + * + * @author Owen Yeo + */ +public class TaskList { + + //ArrayList to store the tasks + private ArrayList tasks = new ArrayList<>(); + + /** + * Constructor for an isntance of TaskList + * + * @param tasks ArrayList for tasks + */ + public TaskList(ArrayList tasks) { + this.tasks = tasks; + } + + /** + * Empty constructor for a TaskList + */ + public TaskList() { + this.tasks = new ArrayList<>(); + } + + /** + * Adds a task to the TaskList + * + * @param taskString representing the descriptor for the task + * @param taskType type of the task getting added + * @throws InvalidDescriptionException + */ + public void addTask(String taskString, TaskType taskType) + throws InvalidDescriptionException { + if (taskString == "") { + throw new InvalidDescriptionException( + "What? Where's your label? Stop this."); + } + + assert taskString.length() > 0 : "Task description cannot be empty"; + + switch(taskType) { + case TODO: + tasks.add(new ToDo(taskString)); + break; + + case DEADLINE: + try { + String[] deadlineParts = taskString.split("/by"); + + assert deadlineParts.length > 1 : "Deadline cannot be empty"; + + tasks.add(new Deadline(deadlineParts[0].trim(), deadlineParts[1].trim())); + } catch (IndexOutOfBoundsException e) { + throw new InvalidDescriptionException( + "Are you stupid? Can you follow instructions?"); + } + break; + + case EVENT: + try { + String[] eventParts = taskString.split("/from"); + + assert eventParts.length > 1 : "Event fromtime cannot be empty"; + + String eventLabel = eventParts[0]; + String[] eventParts2 = eventParts[1].split("/to"); + + assert eventParts2.length > 1 : "Event totime cannot be empty"; + + tasks.add(new Event(eventLabel.trim(), eventParts2[0].trim(), eventParts2[1].trim())); + } catch (IndexOutOfBoundsException e) { + throw new InvalidDescriptionException( + "Are you stupid? Can you follow instructions?"); + } + break; + + default: + break; + } + } + + /** + * Detects if there are duplicate tasks in the list. + * @param labelString the label of the task to check for duplicates. + * @return true if there are duplicates, false otherwise. + */ + public boolean detectDuplicate(String labelString) { + for (int i = 0; i < tasks.size() - 1; i++) { + if (tasks.get(i).getLabel().equals(labelString)) { + return true; + } + } + return false; + } + + /** + * Gets the duplicate tasks in the list. + * @return ArrayList of duplicate tasks. + */ + public ArrayList getDuplicateTasks() { + ArrayList duplicateTasks = new ArrayList<>(); + Set uniqueTasks = new HashSet<>(); + for (Task task : tasks) { + if (!uniqueTasks.add(task.getLabel())) { + duplicateTasks.add(task); + } + } + return duplicateTasks; + } + + /** + * Deletes the duplicate tasks in the list. + */ + public void deleteDuplicates() { + ArrayList duplicateTasks = getDuplicateTasks(); + for (Task task : duplicateTasks) { + tasks.remove(task); + } + } + + /** + * Deletes the item off the list. + * + * @param listNum Index of the item of the list to delete. + */ + public void delete(int listNum) { + int index = listNum - 1; + tasks.remove(index); + } + + /** + * To mark tasks as done. + * + * @param listNum the index of the item on the list to mark. + */ + public void mark(int listNum) throws InvalidIndexException { + Task task = tasks.get(listNum - 1); + task.done(); + } + + /** + * To unmark a list item as undone. + * + * @param listNum Index of the item on the list to unmark. + */ + public void unmark(int listNum) throws InvalidIndexException { + Task task = tasks.get(listNum - 1); + task.undone(); + } + + /** + * To get the list of tasks. + * + * @return ArrayList of tasks. + */ + public Task getTask(int listNum) { + int index = listNum - 1; + return tasks.get(index); + } + + /** + * To get the list of tasks. + * + * @return ArrayList of tasks. + */ + public int getLength() { + return tasks.size(); + } + +} diff --git a/src/main/java/chatbot/task/TaskType.java b/src/main/java/chatbot/task/TaskType.java new file mode 100644 index 0000000000..0f76ccf920 --- /dev/null +++ b/src/main/java/chatbot/task/TaskType.java @@ -0,0 +1,32 @@ +package chatbot.task; + +/** + * Enum representing the different types of tasks. + */ +public enum TaskType { + TODO("T"), + DEADLINE("D"), + EVENT("E"); + + private String input; + + private TaskType(String input) { + this.input = input; + } + + /** + * Parses the input and returns the appropriate command if the input is + * valid. + * + * @param input User's input + * @return Command that tells what the chatbot should do. + */ + public static TaskType parseInput(String input) { + for (TaskType task: TaskType.values()) { + if (task.input.equals(input)) { + return task; + } + } + return null; + } +} diff --git a/src/main/java/chatbot/task/ToDo.java b/src/main/java/chatbot/task/ToDo.java new file mode 100644 index 0000000000..581a90a3eb --- /dev/null +++ b/src/main/java/chatbot/task/ToDo.java @@ -0,0 +1,34 @@ +package chatbot.task; + + +/** + * Todo class that is a task. + * @author Owen Yeo + */ +public class ToDo extends Task { + + /** + * Constructor for a ToDo instance. + * + * @param label descriptor of the tas + */ + public ToDo(String label) { + super(label); + } + + /** + * {@inheritDoc} + */ + @Override + public String toSaveString() { + return "T " + super.toSaveString(); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + return "[T]" + super.toString(); + } +} diff --git a/src/main/java/chatbot/ui/DialogBox.java b/src/main/java/chatbot/ui/DialogBox.java new file mode 100644 index 0000000000..ee2a28d74c --- /dev/null +++ b/src/main/java/chatbot/ui/DialogBox.java @@ -0,0 +1,74 @@ +package chatbot.ui; + + +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; + +/** + * Controller for DialogBox. Provides the layout for the other controls. + */ +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); + } + + /** + * Returns a DialogBox with the user's input and image. + * + * @param text User's input + * @param img User's image + * @return DialogBox with user's input and image + */ + public static DialogBox getUserDialog(String text, Image img) { + return new DialogBox(text, img); + } + + /** + * Returns a DialogBox with the chat bot's response and image. + * + * @param text Chat bot's response + * @param img Chat bot's image + * @return DialogBox with chat bot's response and image + */ + public static DialogBox getChatBotDialog(String text, Image img) { + var db = new DialogBox(text, img); + db.flip(); + return db; + } +} diff --git a/src/main/java/chatbot/ui/Launcher.java b/src/main/java/chatbot/ui/Launcher.java new file mode 100644 index 0000000000..6dd4a7a12c --- /dev/null +++ b/src/main/java/chatbot/ui/Launcher.java @@ -0,0 +1,13 @@ +package chatbot.ui; + +import chatbot.Main; +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/chatbot/ui/MainWindow.java b/src/main/java/chatbot/ui/MainWindow.java new file mode 100644 index 0000000000..4730c799c4 --- /dev/null +++ b/src/main/java/chatbot/ui/MainWindow.java @@ -0,0 +1,68 @@ +package chatbot.ui; + +import chatbot.ChatBot; +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 ChatBot chatBot; + + private Image userImage = new Image(this.getClass().getResourceAsStream("/images/User.jpeg")); + private Image botImage = new Image(this.getClass().getResourceAsStream("/images/Bobby Wasabi.jpeg")); + + @FXML + public void initialize() { + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + } + + public void setChatBot(ChatBot c) { + chatBot = c; + startChat(); + } + + @FXML + private void startChat() { + String response = chatBot.showIntro(); + dialogContainer.getChildren().addAll( + DialogBox.getChatBotDialog(response, botImage) + ); + } + + /** + * 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 = chatBot.getResponse(userInput.getText()); + dialogContainer.getChildren().addAll( + DialogBox.getUserDialog(input, userImage), + DialogBox.getChatBotDialog(response, botImage) + ); + userInput.clear(); + + if (input.equals("bye")) { + System.exit(0); + } + } +} + diff --git a/src/main/java/chatbot/ui/Printer.java b/src/main/java/chatbot/ui/Printer.java new file mode 100644 index 0000000000..f43ef93674 --- /dev/null +++ b/src/main/java/chatbot/ui/Printer.java @@ -0,0 +1,50 @@ +package chatbot.ui; + +/** + * Class representing a Printer that prints outputs + * depending on the command or error. + * + * @author Owen Yeo + */ +public class Printer { + + /** + * Prints the inputs out for the user. + * + * @param inputs + */ + public String print(String[] inputs) { + String output = ""; + for (int i = 0; i < inputs.length; i++) { + if (inputs[i] != null) { + output += inputs[i] + "\n"; + } + } + return output; + } + + + /** + * Prints an introduction. + */ + public String intro() { + return "Hello! I am Bobby Wasabi\nWhat can I do for you today?"; + } + + /** + * Prints a goodbye message. + */ + public String bye() { + return "Bye. Have a bad day you doofus."; + } + + /** + * Prints error messages. + * + * @param e Exception instance. + */ + public String showError(Exception e) { + return "Error! " + e.getMessage(); + } + +} diff --git a/src/main/resources/images/Bobby Wasabi.jpeg b/src/main/resources/images/Bobby Wasabi.jpeg new file mode 100644 index 0000000000..cc745fc183 Binary files /dev/null and b/src/main/resources/images/Bobby Wasabi.jpeg differ diff --git a/src/main/resources/images/User.jpeg b/src/main/resources/images/User.jpeg new file mode 100644 index 0000000000..bfbaba944b Binary files /dev/null and b/src/main/resources/images/User.jpeg differ diff --git a/src/main/resources/scene.fxml b/src/main/resources/scene.fxml new file mode 100644 index 0000000000..4a8c1896ca --- /dev/null +++ b/src/main/resources/scene.fxml @@ -0,0 +1,11 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/main/resources/styles.css b/src/main/resources/styles.css new file mode 100644 index 0000000000..ec1d16e3f6 --- /dev/null +++ b/src/main/resources/styles.css @@ -0,0 +1,3 @@ +.label { + -fx-text-fill: blue; +} \ No newline at end of file diff --git a/src/main/resources/view/DialogBox.fxml b/src/main/resources/view/DialogBox.fxml new file mode 100644 index 0000000000..78f6011440 --- /dev/null +++ b/src/main/resources/view/DialogBox.fxml @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + diff --git a/src/main/resources/view/MainWindow.fxml b/src/main/resources/view/MainWindow.fxml new file mode 100644 index 0000000000..4d89ae5f06 --- /dev/null +++ b/src/main/resources/view/MainWindow.fxml @@ -0,0 +1,19 @@ + + + + + + + + + + + +