diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000000..770e4df969 --- /dev/null +++ b/build.gradle @@ -0,0 +1,56 @@ +plugins { + id 'java' + id 'application' + id 'com.github.johnrengelman.shadow' version '7.1.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("faith.Launcher") +} + +shadowJar { + archiveBaseName = "faith" + archiveClassifier = null +} + +run{ + standardInput = System.in +} diff --git a/data/tasks.txt b/data/tasks.txt new file mode 100644 index 0000000000..cdc1fcef51 --- /dev/null +++ b/data/tasks.txt @@ -0,0 +1,9 @@ +T | 1 | read book +T | 0 | return book +T | 0 | shit +D | 0 | return book | 21/5/2025 1600 +D | 0 | return book | 20/5/2025 +T | 0 | poop +D | 0 | readbook | 10/9/2024 +T | 1 | read book +D | 1 | read book | 10/9/2025 diff --git a/docs/README.md b/docs/README.md index 47b9f984f7..6f512474d1 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,30 +1,156 @@ -# Duke User Guide +# User Guide for Faith -// Update the title above to match the actual product name +Welcome to **Faith**, your personal task manager chatbot. +Faith helps you keep track of tasks, deadlines, and events — all from a simple chat interface. -// Product screenshot goes here +![UI](Ui.png) -// Product intro goes here +--- -## Adding deadlines +## Quick Start -// Describe the action and its outcome. +1. **Launch the app** + - Run the JAR file with `java -jar faith.jar`. + - A GUI window will open. -// Give examples of usage +2. **Type a command** in the text field and hit **Enter** or click **Send**. -Example: `keyword (optional arguments)` +3. **Faith will respond** in the chat window. -// A description of the expected outcome goes here +4. **Exit the app** using the `bye` command or close the chat window. Your tasks are saved automatically. -``` -expected output -``` +--- -## Feature ABC +## Features -// Feature details +### 1. Viewing all tasks: `list` +Shows all the tasks in your list. +**Example:** +list -## Feature XYZ +--- -// Feature details \ No newline at end of file +### 2. Adding a todo: `todo` +Adds a task without a date. + +**Format:** +todo DESCRIPTION + +**Example:** +todo read book + +--- + +### 3. Adding a deadline: `deadline` +Adds a task with a due date (and optionally time). + +**Format:** +deadline DESCRIPTION /by DATE [TIME] + +- DATE can be in formats like `20/5/2025` or `2025-12-02`. +- TIME is optional, e.g., `1600`. + +**Example:** +deadline return book /by 20/5/2025 1800 + +--- + +### 4. Adding an event: `event` +Adds a task with a start and end time. + +**Format:** +event DESCRIPTION /from DATE [TIME] /to DATE [TIME] + +**Example:** +event team meeting /from 20/5/2025 1400 /to 20/5/2025 1600 + +--- + +### 5. Marking/unmarking tasks: `mark` / `unmark` +Marks a task as done or not done. + +**Format:** +mark INDEX +unmark INDEX + +**Example:** +mark 2 +unmark 4 + +--- + +### 6. Deleting tasks: `delete` +Removes a task from the list. + +**Format:** +delete INDEX + +**Example:** +delete 3 + +--- + +### 7. Finding tasks: `find` +Searches for tasks by keyword. + +**Format:** +find KEYWORD + +**Example:** +find book + +--- + +### 8. Editing tasks: `edit` +Update a task without deleting it first. You can change only **one field at a time**. + +**Formats:** +edit INDEX /desc NEW_DESCRIPTION +edit INDEX /by NEW_DATE [TIME] (for deadlines) +edit INDEX /from NEW_DATE [TIME] (for events) +edit INDEX /to NEW_DATE [TIME] (for events) + +**Examples:** +edit 2 /desc read another book +edit 3 /by 21/5/2025 1800 +edit 4 /to 1/6/2025 1030 + +--- + +### 9. Exiting: `bye` +Exits the app. Your tasks are saved automatically. + +**Example:** +bye + +--- + +## FAQ + +**Q: Where are my tasks saved?** +A: In the `data/tasks.txt` file in the same folder as the app. They will load automatically next time you run Faith. + +**Q: What happens if I type the wrong command?** +A: Faith will tell you what went wrong and show the correct format. + +--- + +## Command Summary + +| Command | Format (examples) | +|----------|---------------------------------------------------------| +| list | `list` | +| todo | `todo read book` | +| deadline | `deadline return book /by 20/5/2025 1800` | +| event | `event meeting /from 20/5/2025 1400 /to 20/5/2025 1600` | +| mark | `mark 2` | +| unmark | `unmark 2` | +| delete | `delete 3` | +| find | `find book` | +| edit | `edit 2 desc/ read another book` | +| bye | `bye` | + +--- + +*End of User Guide* \ No newline at end of file diff --git a/docs/Ui.png b/docs/Ui.png new file mode 100644 index 0000000000..11b764174b 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/faith/Faith.java b/src/main/java/faith/Faith.java new file mode 100644 index 0000000000..5ebf9e04b7 --- /dev/null +++ b/src/main/java/faith/Faith.java @@ -0,0 +1,85 @@ +package faith; + +import faith.exception.*; +import faith.io.BufferedUi; +import faith.io.Storage; +import faith.io.Ui; +import faith.logic.Parser; +import faith.logic.command.Command; +import faith.model.TaskList; + +/** + * Entry point of the Faith application. + * Wires together UI, storage, task list, and the command loop. + */ +public class Faith { + private Storage storage; + private TaskList tasks; + private Ui ui; + + /** + * Creates a new Faith instance and attempts to load tasks from the given file path. + * + * @param filePath path to the storage tasks file (e.g., "data/tasks.txt"). + */ + public Faith(String filePath) { + this.ui = new Ui(); + this.storage = new Storage(filePath); + try { + tasks = new TaskList(storage.load()); + } catch (FaithException e) { + ui.showLoadingError(); + tasks = new TaskList(); + } + } + + public String getResponse(String input) { + BufferedUi bui = new BufferedUi(); + + try { + Command c = Parser.parse(input); + c.execute(tasks, bui, storage); + String reply = bui.drain(); + if (reply.isEmpty()) reply = "OK."; + return reply; + } catch (FaithException e) { + bui.showError(e.getMessage()); + return bui.drain(); + } catch (Exception e) { + return "Unexpected error: " + e.getMessage(); + } + } + + /** + * Runs the main event loop: + * reads commands, executes them, handles errors, and decides when to exit. + */ + public void run() { + ui.showWelcome(); + boolean isExit = false; + while (!isExit) { + try { + String fullCommand = ui.readCommand(); + ui.showLine(); // show the divider line ("_______") + Command c = Parser.parse(fullCommand); + c.execute(tasks, ui, storage); + isExit = c.isExit(); + } catch (FaithException e) { + ui.showError(e.getMessage()); + } finally { + ui.showLine(); + } + } + } + + /** + * Launches the application. + * + * @param args command line arguments (unused). + */ + public static void main (String[] args) { + new Faith("data/tasks.txt").run(); + } + +} + diff --git a/src/main/java/faith/FaithApp.java b/src/main/java/faith/FaithApp.java new file mode 100644 index 0000000000..a3128ca30e --- /dev/null +++ b/src/main/java/faith/FaithApp.java @@ -0,0 +1,23 @@ +package faith; + +import faith.ui.MainWindow; +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Scene; +import javafx.stage.Stage; + +public class FaithApp extends Application { + private Faith faith = new Faith("data/tasks.txt"); + + @Override + public void start(Stage stage) throws Exception { + FXMLLoader fxmlLoader = new FXMLLoader(FaithApp.class.getResource("/view/MainWindow.fxml")); + Scene scene = new Scene(fxmlLoader.load()); + MainWindow controller = fxmlLoader.getController(); + controller.setFaith(faith); + + stage.setTitle("Faith"); + stage.setScene(scene); + stage.show(); + } +} diff --git a/src/main/java/faith/Launcher.java b/src/main/java/faith/Launcher.java new file mode 100644 index 0000000000..14c3205fca --- /dev/null +++ b/src/main/java/faith/Launcher.java @@ -0,0 +1,9 @@ +package faith; + +import javafx.application.Application; + +public class Launcher { + public static void main(String[] args) { + Application.launch(FaithApp.class, args); + } +} diff --git a/src/main/java/faith/exception/FaithException.java b/src/main/java/faith/exception/FaithException.java new file mode 100644 index 0000000000..93ab23792a --- /dev/null +++ b/src/main/java/faith/exception/FaithException.java @@ -0,0 +1,24 @@ +package faith.exception; + +/** + * checked exception for recoverable errors. + * (e.g., unscripted commands, I/O failures). + */ +public class FaithException extends Exception { + + /** + * Constructs a new {@code FaithException} with a human-readable message. + * + * @param msg reason for the failure. + */ + public FaithException(String msg) { + super(msg); + } + + /** + * Constructs a new {@code FaithException}. + */ + public FaithException() { + super(); + } +} \ No newline at end of file diff --git a/src/main/java/faith/io/BufferedUi.java b/src/main/java/faith/io/BufferedUi.java new file mode 100644 index 0000000000..d2959da978 --- /dev/null +++ b/src/main/java/faith/io/BufferedUi.java @@ -0,0 +1,56 @@ +package faith.io; + +public class BufferedUi extends Ui { + private final StringBuilder sb = new StringBuilder(); + + /** + * Prints a friendly greeting at program start. + */ + @Override + public void showWelcome() { + sb.append("Hello! I'm Faith\nWhat can I do for you?\n"); + } + + /** + * Prints a goodbye message just before the program exits. + */ + @Override + public void showGoodbye() { + sb.append("Bye. Hope to see you again soon!\n"); + } + + /** + * Prints a message. + * + * @param message text to print. + */ + @Override + public void show(String message) { + sb.append(message).append('\n'); + } + + /** + * Prints an error message . + * + * @param message description of the error. + */ + @Override + public void showError(String message) { + sb.append(message).append('\n'); + } + + /** + * Prints a specific message when loading stored tasks fails. + */ + @Override + public void showLoadingError() { + sb.append("Oops, I couldn't load your tasks. Starting fresh.\n"); + } + + /** Returns accumulated text and clears the buffer. */ + public String drain() { + String out = sb.toString().trim(); + sb.setLength(0); + return out; + } +} diff --git a/src/main/java/faith/io/Storage.java b/src/main/java/faith/io/Storage.java new file mode 100644 index 0000000000..fc4696b393 --- /dev/null +++ b/src/main/java/faith/io/Storage.java @@ -0,0 +1,120 @@ +package faith.io; + +import faith.exception.FaithException; +import faith.logic.Parser; +import faith.model.TaskList; +import faith.model.task.*; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.List; + +/** + * Store tasks to disk and loads them back on startup. + * Storage format is string text, one task per line. + */ +public class Storage { + + private final String filePath; + + /** + * Creates a storage with the given file path. + * + * @param filePath path to the tasks file. + */ + public Storage(String filePath) { + this.filePath = filePath; + } + + /** + * Loads tasks from disk. Creates the file if missing. + * + * @return a list of tasks loaded from storage. + * @throws FaithException if the file cannot be read or parsed. + */ + public List load() throws FaithException { + TaskList taskList = new TaskList(); + Path path = Paths.get(filePath); + + try { + // NEW: ensure parent dir + file exist on first run + if (Files.notExists(path)) { + Path parent = path.getParent(); + if (parent != null) { + Files.createDirectories(parent); + } + Files.createFile(path); + return taskList.asList(); // empty list + } + + try (BufferedReader br = Files.newBufferedReader(path)) { + String line; + while ((line = br.readLine()) != null) { + String[] parts = line.split("\\|"); // storage: "T | 1 | desc | extra" + if (parts.length < 3) { + continue; + } + String taskType = parts[0].trim(); + String description = parts[2].trim(); + + if (taskType.equals("T")) { + Task task = new Todo(description); + taskList.add(task); + if (parts[1].trim().equals("1")) { + task.markDone(); + } + } + + if (taskType.equals("D")) { + if (parts.length < 4) { + continue; + } + Task task = new Deadline(description, parts[3].trim()); + taskList.add(task); + if (parts[1].trim().equals("1")) { + task.markDone(); + } + } + + if (taskType.equals("E")) { + if (parts.length < 4) { + continue; + } + String[] timeParts = parts[3].trim().split("-"); + if (timeParts.length != 2) { + continue; + } + Task task = new Event(description, timeParts[0].trim(), timeParts[1].trim()); + taskList.add(task); + if (parts[1].trim().equals("1")) { + task.markDone(); + } + } + } + } + } catch (IOException e) { + throw new FaithException("Failed to load tasks from " + filePath + ": " + e.getMessage()); + } + return taskList.asList(); + } + + /** + * Saves the task list to disk, overwriting the file. + * + * @param tasks the task list to store. + * @throws FaithException if writing fails. + */ + public void save(TaskList tasks) throws FaithException { + try (BufferedWriter bw = new BufferedWriter(new FileWriter(filePath))) { + for (Task t : tasks.asList()) { + bw.write(t.saveToFileFormat()); + bw.newLine(); + } + } catch (IOException e) { + throw new FaithException(); + } + } +} \ No newline at end of file diff --git a/src/main/java/faith/io/Ui.java b/src/main/java/faith/io/Ui.java new file mode 100644 index 0000000000..2f57f65f4f --- /dev/null +++ b/src/main/java/faith/io/Ui.java @@ -0,0 +1,68 @@ +package faith.io; + +import java.util.Scanner; + +/** + * Handles all user interaction: reading commands and printing messages. + * Keeps business logic out of I/O code. + */ +public class Ui { + private final Scanner in = new Scanner(System.in); + + /** + * Prints a friendly greeting at program start. + */ + public void showWelcome() { + System.out.println(" ____________________________________________________________\n" + + " Hello! I'm Faith\n" + " What can I do for you?\n" + + " ____________________________________________________________"); + } + + /** + * Prints a goodbye message just before the program exits. + */ + public void showGoodbye() { + System.out.println(" Bye. Hope to see you again soon!"); + } + + /** + * Prints a horizontal divider line for visual separation. + */ + public void showLine() { + System.out.println(" ____________________________________________________________"); + } + + /** + * Prints a message. + * + * @param message text to print. + */ + public void show(String message) { + System.out.println(message); + } + + /** + * Prints an error message . + * + * @param message description of the error. + */ + public void showError(String message) { + System.out.println(message); + } + + /** + * Prints a specific message when loading stored tasks fails. + */ + public void showLoadingError() { + System.out.println(" OOPS!!! I couldn't load your tasks. Starting fresh."); + } + + /** + * Reads a full line of single command fron user input. + * + * @return the original command line. + */ + public String readCommand() { + return in.nextLine(); + } +} diff --git a/src/main/java/faith/logic/Parser.java b/src/main/java/faith/logic/Parser.java new file mode 100644 index 0000000000..d6d6d0a7db --- /dev/null +++ b/src/main/java/faith/logic/Parser.java @@ -0,0 +1,136 @@ +package faith.logic; + +import faith.exception.FaithException; +import faith.logic.command.*; + +/** + * Parses user input strings into executable {@link Command} objects. + * Responsible only for syntactic interpretation; execution happens in commands. + */ +public class Parser { + + /** + * Parses the original user command into a specific {@link Command} instance. + *

+ * Supported commands include: list, bye, todo, deadline, event, mark, unmark, delete. + * + * @param input the command line input from user. + * @return a {@link Command} instance. + * @throws FaithException if the command is unknown or arguments are invalid. + */ + public static Command parse(String input) throws FaithException { + assert input != null : "parse input must not be null"; + String s = input.trim(); + if (s.equals("bye")) return new ExitCommand(); + if (s.equals("list")) return new ListCommand(); + + if (s.startsWith("mark ")) { + int idx = Integer.parseInt(s.substring(5).trim()); + assert idx > 0 : "mark: index must be > 0"; + if (idx <= 0) { + throw new FaithException("Index must be a positive integer."); + } + return new MarkCommand(idx); + } + if (s.startsWith("unmark ")) { + int idx = Integer.parseInt(s.substring(7).trim()); + assert idx > 0 : "unmark: index must be > 0"; + if (idx <= 0) { + throw new FaithException("Index must be a positive integer."); + } + return new UnmarkCommand(idx); + } + if (s.startsWith("delete ")) { + int idx = Integer.parseInt(s.substring(7).trim()); + assert idx > 0 : "delete: index must be > 0"; + if (idx <= 0) { + throw new FaithException("Index must be a positive integer."); + } + return new DeleteCommand(idx); + } + if (s.startsWith("todo ")) { + String desc = s.substring(5).trim(); + if (desc.isEmpty()) throw new FaithException(" The description of a todo cannot be empty."); + return new AddTodoCommand(desc); + } + if (s.startsWith("deadline ")) { + int i = s.indexOf(" /by "); + if (i < 0) throw new FaithException(" Use: deadline /by "); + String desc = s.substring(9, i).trim(); + String by = s.substring(i + 5).trim(); + if (desc.isEmpty() || by.isEmpty()) + throw new FaithException(" Deadline needs both description and /by."); + return new AddDeadlineCommand(desc, by); + } + if (s.startsWith("event ")) { + int i = s.indexOf(" /from "); + int j = s.indexOf(" /to "); + if (i < 0) + throw new FaithException(" Use: event /from /to "); + String desc = s.substring(6, i).trim(); + String from = s.substring(i + 7).trim(); + String to = s.substring(j + 5).trim(); + if (desc.isEmpty() || from.isEmpty() || to.isEmpty()) + throw new FaithException(" Deadline needs description, /from and /to."); + return new AddEventCommand(desc, from, to); + } + if (s.startsWith("find ")) { + String keyword = s.substring(5).trim(); + if (keyword.isEmpty()) { + throw new FaithException(" Find keywords cannot be empty."); + } + return new FindCommand(keyword); + } + //Ask chatgpt on idea of writing simple code for this + if (s.startsWith("edit ")) { + // Format (one field only): + // edit /desc + // edit /by + // edit /from + // edit /to + String remainder = s.substring(5).trim(); + int sp = remainder.indexOf(' '); + if (sp < 0) throw new FaithException("Use: edit / "); + + int idx = Integer.parseInt(remainder.substring(0, sp).trim()) - 1; + assert idx >= 0 : "edit: index must be > 0"; + String args = remainder.substring(sp + 1).trim(); + + int posDesc = args.indexOf("/desc"); + int posBy = args.indexOf("/by"); + int posFrom = args.indexOf("/from"); + int posTo = args.indexOf("/to"); + + int count = 0; + if (posDesc == 0) count++; + if (posBy == 0) count++; + if (posFrom == 0) count++; + if (posTo == 0) count++; + + if (count != 1) { + throw new FaithException("Provide exactly one field: /desc | /by | /from | /to"); + } + + if (posDesc == 0) { + String val = args.substring(5).trim(); + if (val.isEmpty()) throw new FaithException("/desc cannot be empty."); + return new EditCommand(idx, EditCommand.Field.DESC, val); + } + if (posBy == 0) { + String val = args.substring(3).trim(); + if (val.isEmpty()) throw new FaithException("/by cannot be empty."); + return new EditCommand(idx, EditCommand.Field.BY, val); + } + if (posFrom == 0) { + String val = args.substring(5).trim(); + if (val.isEmpty()) throw new FaithException("/from cannot be empty."); + return new EditCommand(idx, EditCommand.Field.FROM, val); + } + // posTo == 0 + String val = args.substring(3).trim(); + if (val.isEmpty()) throw new FaithException("/to cannot be empty."); + return new EditCommand(idx, EditCommand.Field.TO, val); + } + throw new FaithException(" Sorry, I don't understand."); + } +} diff --git a/src/main/java/faith/logic/command/AddDeadlineCommand.java b/src/main/java/faith/logic/command/AddDeadlineCommand.java new file mode 100644 index 0000000000..bfed48b042 --- /dev/null +++ b/src/main/java/faith/logic/command/AddDeadlineCommand.java @@ -0,0 +1,39 @@ +package faith.logic.command; + +import faith.exception.FaithException; +import faith.io.Storage; +import faith.io.Ui; +import faith.model.TaskList; +import faith.model.task.Deadline; + +/** + * Adds a new {@code Deadline} task with a due date/time string. + * The {@code Deadline} class is responsible for parsing the date/time. + */ +public class AddDeadlineCommand extends Command { + private final String desc; + private final String by; + + /** + * Creates a command to add a Deadline task with the given description. + * @param desc non-empty task description. + * @param by deadline datetime of task (e.g., 20/9/2025 1600). + */ + public AddDeadlineCommand(String desc, String by) { + this.desc = desc; + this.by = by; + } + + /** + * Executes: adds the deadline task, shows feedback, and saves. + */ + @Override + public void execute(TaskList tasks, Ui ui, Storage storage) throws FaithException { + Deadline t = new Deadline(desc, by); + tasks.add(t); + ui.show(" Got it. I've added this task:"); + ui.show(" " + t.toString()); + ui.show(" Now you have " + tasks.size() + " tasks in the list."); + storage.save(tasks); + } +} \ No newline at end of file diff --git a/src/main/java/faith/logic/command/AddEventCommand.java b/src/main/java/faith/logic/command/AddEventCommand.java new file mode 100644 index 0000000000..22b8bc7759 --- /dev/null +++ b/src/main/java/faith/logic/command/AddEventCommand.java @@ -0,0 +1,41 @@ +package faith.logic.command; + +import faith.exception.FaithException; +import faith.io.Storage; +import faith.io.Ui; +import faith.model.TaskList; +import faith.model.task.Event; + +/** + * Adds a new {@code Event} task to the list. + */ +public class AddEventCommand extends Command { + private final String desc; + private final String from; + private final String to; + + /** + * Creates a command to add a Event task with given description, start time and end time. + * @param desc the task description. + * @param from the start time of the event task. + * @param to the end time of the event task. + */ + public AddEventCommand(String desc, String from, String to) { + this.desc = desc; + this.from = from; + this.to = to; + } + + /** + * Executes: adds the event task, shows feedback, and saves. + */ + @Override + public void execute(TaskList tasks, Ui ui, Storage storage) throws FaithException { + Event e = new Event(desc, from, to); + tasks.add(e); + ui.show(" Got it. I've added this task:"); + ui.show(" " + e.toString()); + ui.show(" Now you have " + tasks.size() + " tasks in the list."); + storage.save(tasks); + } +} \ No newline at end of file diff --git a/src/main/java/faith/logic/command/AddTodoCommand.java b/src/main/java/faith/logic/command/AddTodoCommand.java new file mode 100644 index 0000000000..e74a83d405 --- /dev/null +++ b/src/main/java/faith/logic/command/AddTodoCommand.java @@ -0,0 +1,36 @@ +package faith.logic.command; + +import faith.exception.FaithException; +import faith.io.Storage; +import faith.io.Ui; +import faith.model.TaskList; +import faith.model.task.Todo; + +/** + * Adds a new {@code Todo} task to the list. + */ +public class AddTodoCommand extends Command { + + private String desc; + /** + * Creates a command to add a Todo task with the given description. + * + * @param desc non-empty task description. + */ + public AddTodoCommand(String desc) { + this.desc = desc; + } + + /** + * Executes: adds the todo task, shows feedback, and saves. + */ + @Override + public void execute(TaskList tasks, Ui ui, Storage storage) throws FaithException { + Todo t = new Todo(desc); + tasks.add(t); + ui.show(" Got it. I've added this task:"); + ui.show(" " + t.toString()); + ui.show(" Now you have " + tasks.size() + " tasks in the list."); + storage.save(tasks); + } +} \ No newline at end of file diff --git a/src/main/java/faith/logic/command/Command.java b/src/main/java/faith/logic/command/Command.java new file mode 100644 index 0000000000..33a3ba63f2 --- /dev/null +++ b/src/main/java/faith/logic/command/Command.java @@ -0,0 +1,30 @@ +package faith.logic.command; + +import faith.exception.FaithException; +import faith.io.Storage; +import faith.io.Ui; +import faith.model.TaskList; + +/** + * Base class for all user commands such as marking, deleting, or exiting. + */ +public abstract class Command { + + /** + * Executes the command against the given collaborators. + * + * @param tasks task list. + * @param ui the UI to show messages to the user. + * @param storage the storage used to store task list. + * @throws FaithException error during execution. + */ + public abstract void execute(TaskList tasks, Ui ui, Storage storage) throws FaithException; + + /** + * + * @return true if it is an exit command, false otherwise. + */ + public boolean isExit() { + return false; + } +} \ No newline at end of file diff --git a/src/main/java/faith/logic/command/DeleteCommand.java b/src/main/java/faith/logic/command/DeleteCommand.java new file mode 100644 index 0000000000..ab00391066 --- /dev/null +++ b/src/main/java/faith/logic/command/DeleteCommand.java @@ -0,0 +1,34 @@ +package faith.logic.command; + +import faith.exception.FaithException; +import faith.io.Storage; +import faith.io.Ui; +import faith.model.TaskList; + +/** + * Deletes a task from the list by index. + */ +public class DeleteCommand extends Command { + + private final int idx; + + /** + * Constructs a deletion command for the given 1-based index. + * + * @param idx position of the task on the UI to remove. + */ + public DeleteCommand(int idx) { + this.idx = idx; + } + + /** + * Executes: removes the task, shows feedback, and saves the new list. + */ + @Override + public void execute(TaskList tasks, Ui ui, Storage storage) throws FaithException { + ui.show(" Noted. I've removed this task:"); + ui.show(" " + tasks.remove(this.idx - 1).toString()); + ui.show(" Now you have " + tasks.size() + " tasks in the list."); + storage.save(tasks); + } +} diff --git a/src/main/java/faith/logic/command/EditCommand.java b/src/main/java/faith/logic/command/EditCommand.java new file mode 100644 index 0000000000..f3ab124ee1 --- /dev/null +++ b/src/main/java/faith/logic/command/EditCommand.java @@ -0,0 +1,80 @@ +package faith.logic.command; + +import faith.exception.FaithException; +import faith.io.Storage; +import faith.io.Ui; +import faith.model.TaskList; +import faith.model.task.Deadline; +import faith.model.task.Event; +import faith.model.task.Task; + +/** + * Edit existing task + */ +public class EditCommand extends Command { + public enum Field { DESC, BY, FROM, TO } + + private final int index; // 0-based + private final Field field; + private final String value; + + /** + * Constructs an edit command. + * + * @param field which is getting edited + */ + public EditCommand(int index, Field field, String value) { + this.index = index; + this.field = field; + this.value = value; + } + + /** + * Edit a task's description, deadline, start or end time + * + * @param tasks task list. + * @param ui the UI to show messages to the user. + * @param storage the storage used to store task list. + * @throws FaithException + */ + @Override + public void execute(TaskList tasks, Ui ui, Storage storage) throws FaithException { + if (index < 0 || index >= tasks.size()) { + throw new FaithException("Index out of range."); + } + Task t = tasks.get(index); + String before = t.toString(); + + switch (field) { + case DESC: + t.setDescription(value); + break; + case BY: + if (t instanceof Deadline) { + ((Deadline) t).setBy(value); + } else { + throw new FaithException("Field '/by' applies only to deadlines."); + } + break; + case FROM: + if (t instanceof Event) { + ((Event) t).setFrom(value); + } else { + throw new FaithException("Field '/from' applies only to events."); + } + break; + case TO: + if (t instanceof Event) { + ((Event) t).setTo(value); + } else { + throw new FaithException("Field '/to' applies only to events."); + } + break; + default: + throw new FaithException("Unknown field."); + } + + storage.save(tasks); + ui.show("Edited task:\n before: " + before + "\n after: " + t); + } +} \ No newline at end of file diff --git a/src/main/java/faith/logic/command/ExitCommand.java b/src/main/java/faith/logic/command/ExitCommand.java new file mode 100644 index 0000000000..ea2003e38d --- /dev/null +++ b/src/main/java/faith/logic/command/ExitCommand.java @@ -0,0 +1,27 @@ +package faith.logic.command; + +import faith.io.Storage; +import faith.io.Ui; +import faith.model.TaskList; + +/** + * Tell the application to exit after showing a goodbye message. + */ +public class ExitCommand extends Command { + + /** + * + * @return always true because this is an exit command. + */ + public boolean isExit() { + return true; + } + + /** + * Executes: prints the goodbye message. + */ + @Override + public void execute(TaskList tasks, Ui ui, Storage storage) { + ui.showGoodbye(); + } +} diff --git a/src/main/java/faith/logic/command/FindCommand.java b/src/main/java/faith/logic/command/FindCommand.java new file mode 100644 index 0000000000..71ace0f3f5 --- /dev/null +++ b/src/main/java/faith/logic/command/FindCommand.java @@ -0,0 +1,44 @@ +package faith.logic.command; + +import faith.io.Storage; +import faith.io.Ui; +import faith.model.TaskList; +import faith.model.task.Task; + +/** + * Find tasks in task list by keyword given. + */ +public class FindCommand extends Command { + private String keyword; + + /** + * Constructs a find command. + * + * @param keyword the keyword to find task + */ + public FindCommand(String keyword) { + this.keyword = keyword; + } + + /** + * Find tasks with the given keyword and list them out if any + * + * @param tasks task list. + * @param ui the UI to show messages to the user. + * @param storage the storage used to store task list. + */ + @Override + public void execute(TaskList tasks, Ui ui, Storage storage) { + TaskList findList = new TaskList(); + for (int i = 0; i < tasks.size(); i++) { + Task currentTask = tasks.get(i); + if (currentTask.getDescription().toLowerCase().contains(keyword.toLowerCase())) { + findList.add(currentTask); + } + } + ui.show(" Here are the matching tasks in your list:"); + for (int i = 0; i < findList.size(); i++) { + ui.show(" " + (i + 1) + "." + findList.get(i)); + } + } +} \ No newline at end of file diff --git a/src/main/java/faith/logic/command/ListCommand.java b/src/main/java/faith/logic/command/ListCommand.java new file mode 100644 index 0000000000..d1ceb79f62 --- /dev/null +++ b/src/main/java/faith/logic/command/ListCommand.java @@ -0,0 +1,22 @@ +package faith.logic.command; + +import faith.io.Storage; +import faith.io.Ui; +import faith.model.TaskList; + +/** + * Print the task list in their natural order. + */ +public class ListCommand extends Command { + + /** + * Executes: prints either an empty message or a numbered list of tasks. + */ + @Override + public void execute(TaskList tasks, Ui ui, Storage storage) { + ui.show(" Here are the tasks in your list:"); + for (int i = 0; i < tasks.size(); i++) { + ui.show(" " + (i + 1) + "." + tasks.get(i)); + } + } +} \ No newline at end of file diff --git a/src/main/java/faith/logic/command/MarkCommand.java b/src/main/java/faith/logic/command/MarkCommand.java new file mode 100644 index 0000000000..47789347f3 --- /dev/null +++ b/src/main/java/faith/logic/command/MarkCommand.java @@ -0,0 +1,34 @@ +package faith.logic.command; + +import faith.exception.FaithException; +import faith.io.Storage; +import faith.io.Ui; +import faith.model.TaskList; +import faith.model.task.Task; + +/** + * Mark a task as done by its displaying index. + */ +public class MarkCommand extends Command { + + private int idx; + + /** + * Creates a command to mark a task as done with the given displaying index. + */ + public MarkCommand(int idx) { + this.idx = idx; + } + + /** + * Executes: marks the task as done, shows feedback, and saves the change. + */ + @Override + public void execute(TaskList tasks, Ui ui, Storage storage) throws FaithException { + Task targetTask = tasks.get(idx - 1); + targetTask.markDone(); + ui.show(" Nice! I've marked this task as done:"); + ui.show(" " + targetTask); + storage.save(tasks); + } +} \ No newline at end of file diff --git a/src/main/java/faith/logic/command/UnmarkCommand.java b/src/main/java/faith/logic/command/UnmarkCommand.java new file mode 100644 index 0000000000..791bc76675 --- /dev/null +++ b/src/main/java/faith/logic/command/UnmarkCommand.java @@ -0,0 +1,33 @@ +package faith.logic.command; + +import faith.exception.FaithException; +import faith.io.Storage; +import faith.io.Ui; +import faith.model.TaskList; +import faith.model.task.Task; +/** + * Marks a task as not done by its displaying index. + */ +public class UnmarkCommand extends Command { + + private int idx; + + /** + * Creates a command to mark a task as not done with the given displaying index. + */ + public UnmarkCommand(int idx) { + this.idx = idx; + } + + /** + * Executes: marks the task as not done, shows feedback, and saves the change. + */ + @Override + public void execute(TaskList tasks, Ui ui, Storage storage) throws FaithException { + Task targetTask = tasks.get(idx - 1); + targetTask.unmarkDone(); + ui.show(" OK, I've marked this task as not done yet:"); + ui.show(" " + targetTask); + storage.save(tasks); + } +} \ No newline at end of file diff --git a/src/main/java/faith/model/TaskList.java b/src/main/java/faith/model/TaskList.java new file mode 100644 index 0000000000..cd5a0824b0 --- /dev/null +++ b/src/main/java/faith/model/TaskList.java @@ -0,0 +1,86 @@ +package faith.model; + +import faith.model.task.Task; +import java.util.ArrayList; +import java.util.List; + +public class TaskList { + + private final ArrayList taskList; + + /** + * Returns a new empty task list. + */ + public TaskList() { + this.taskList = new ArrayList<>(); + } + + /** + * Constructs a task list from given list. + * + * @param initial returns a task list constructed with given list. + */ + public TaskList(List initial) { + this.taskList = new ArrayList<>(initial); + } + + /** + * Returns the number of tasks in the list. + * + * @return the number of tasks in the list. + */ + public int size() { + return taskList.size(); + } + + /** + * Returns the task at the specified position in this list. + * + * @param index index of the task to return. + * @return the task at the specified position in this list. + */ + public Task get(int index) { + return taskList.get(index); + } + + /** + * Appends the specified task to the end of this list. + * + * @param t task to be appended to this list. + */ + public void add(Task t) { + taskList.add(t); + } + + /** + * Inserts the specified task at the specified position in this list. + * Shifts the task currently at that position (if any) + * and any subsequent tasks to the right (adds one to their indices). + * + * @param index index at which the specified element is to be inserted + * @param t task to be inserted + */ + public void add(int index, Task t) { + taskList.add(index, t); + } + + /** + * Removes the task at the specified position in this list. + * Shifts any subsequent tasks to the left (subtracts one from their indices). + * + * @param index the index of the task to be removed. + * @return the task that was removed from the list. + */ + public Task remove(int index) { + return taskList.remove(index); + } + + /** + * return task list. + * + * @return task list. + */ + public List asList() { + return taskList; + } +} \ No newline at end of file diff --git a/src/main/java/faith/model/task/Deadline.java b/src/main/java/faith/model/task/Deadline.java new file mode 100644 index 0000000000..4a607ad9fc --- /dev/null +++ b/src/main/java/faith/model/task/Deadline.java @@ -0,0 +1,136 @@ +package faith.model.task; + +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * A task with a due date/time. + */ +public class Deadline extends Task { + + protected String by; + + private LocalDateTime byDateTime; + + private boolean hasTime; + + private static final DateTimeFormatter DMYHHMM = DateTimeFormatter.ofPattern("d/M/uuuu HHmm"); + private static final DateTimeFormatter DMYHHMM_ = DateTimeFormatter.ofPattern("d-M-uuuu HHmm"); + private static final DateTimeFormatter DMY = DateTimeFormatter.ofPattern("d/M/uuuu"); + private static final DateTimeFormatter DMY_ = DateTimeFormatter.ofPattern("d-M-uuuu"); + private static final DateTimeFormatter YMD = DateTimeFormatter.ofPattern("uuuu/M/d"); + private static final DateTimeFormatter ISO_DATE = DateTimeFormatter.ISO_LOCAL_DATE; + + /** + * Creates a deadline with the given description and raw date/time string. + * + * @param description description of the task. + * @param by due date/time of tge task (e.g., "20/5/2025" or "20/5/2025 1600" or "2025-12-02"). + */ + public Deadline(String description, String by) { + super(description); + this.by = by; + try { + byDateTime = LocalDateTime.parse(by, DMYHHMM); + hasTime = true; + } catch (DateTimeParseException e) {} + + if (byDateTime == null) { + try { + byDateTime = LocalDateTime.parse(by, DMYHHMM_); + hasTime = true; + } catch (DateTimeParseException e) {} + } + + if (byDateTime == null) { + try { + byDateTime = LocalDate.parse(by, DMY).atStartOfDay(); + } catch (DateTimeParseException ignore) {} + } + if (byDateTime == null) { + try { + byDateTime = LocalDate.parse(by, DMY_).atStartOfDay(); + } catch (DateTimeParseException ignore) {} + } + if (byDateTime == null) { + try { + byDateTime = LocalDate.parse(by, YMD).atStartOfDay(); + } catch (DateTimeParseException ignore) {} + } + if (byDateTime == null) { + try { + byDateTime = LocalDate.parse(by, ISO_DATE).atStartOfDay(); + } catch (DateTimeParseException ignore) {} + } + } + + /** + * Edit the task due time. + * + * @param newBy the new due time + */ + public void setBy(String newBy) { + this.by = newBy.trim(); + this.hasTime = false; + this.byDateTime = null; + try { + byDateTime = LocalDateTime.parse(by, DMYHHMM); + hasTime = true; + } catch (DateTimeParseException e) {} + + if (byDateTime == null) { + try { + byDateTime = LocalDateTime.parse(by, DMYHHMM_); + hasTime = true; + } catch (DateTimeParseException e) {} + } + + if (byDateTime == null) { + try { + byDateTime = LocalDate.parse(by, DMY).atStartOfDay(); + } catch (DateTimeParseException ignore) {} + } + if (byDateTime == null) { + try { + byDateTime = LocalDate.parse(by, DMY_).atStartOfDay(); + } catch (DateTimeParseException ignore) {} + } + if (byDateTime == null) { + try { + byDateTime = LocalDate.parse(by, YMD).atStartOfDay(); + } catch (DateTimeParseException ignore) {} + } + if (byDateTime == null) { + try { + byDateTime = LocalDate.parse(by, ISO_DATE).atStartOfDay(); + } catch (DateTimeParseException ignore) {} + } + } + + /** + * Converts this deadline to the storage line format. + * + * @return storage record line. + */ + @Override + public String saveToFileFormat() { + return "D | " + this.isDoneInt() + " | " + description + " | " + by; + } + + /** + * Returns a user-friendly representation including the pretty-printed date/time. + * + * @return human-readable string for UI. + */ + @Override + public String toString() { + return "[D]" + super.toString() + + " (by: " + (byDateTime == null + ? this.by + : (byDateTime.toLocalDate().format(DateTimeFormatter.ofPattern("MMM d uuuu")) + + (hasTime ? ", " + byDateTime.toLocalTime().format(DateTimeFormatter.ofPattern("h:mma")) : ""))) + + ")"; + } +} \ No newline at end of file diff --git a/src/main/java/faith/model/task/Event.java b/src/main/java/faith/model/task/Event.java new file mode 100644 index 0000000000..76743b5cbf --- /dev/null +++ b/src/main/java/faith/model/task/Event.java @@ -0,0 +1,59 @@ +package faith.model.task; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * Event with description, start and end time. + */ +public class Event extends Task { + protected String fromTime; + protected String toTime; + + /** + * Create an Event instance with description, start time and end time. + * + * @param description the description of the event. + * @param fromTime the time event start. + * @param toTime the time event end. + */ + public Event(String description, String fromTime, String toTime) { + super(description); + this.fromTime = fromTime; + this.toTime = toTime; + } + + /** + * Change event start time. + * + * @param newFrom the new event start time. + */ + public void setFrom(String newFrom) { + this.fromTime = newFrom; + } + + /** + * Change event end time. + * + * @param newTo the new event end time. + */ + public void setTo(String newTo) { + this.toTime = newTo; + } + + /** + * Save the event in a format to be stored in a file + * + * @return the event in stored format + */ + @Override + public String saveToFileFormat() { + return "T | " + this.isDoneInt() + " | " + description + " | " + fromTime + "-" + toTime; + } + + @Override + public String toString() { + return "[E]" + super.toString() + " (from: " + fromTime + " to: " + toTime + ")"; + } +} \ No newline at end of file diff --git a/src/main/java/faith/model/task/Task.java b/src/main/java/faith/model/task/Task.java new file mode 100644 index 0000000000..f6f27c7698 --- /dev/null +++ b/src/main/java/faith/model/task/Task.java @@ -0,0 +1,41 @@ +package faith.model.task; + +public class Task { + public String description; + protected boolean isDone; + + public Task(String description) { + this.description = description; + this.isDone = false; + } + + public String getDescription() { + return this.description; + } + + public void setDescription(String description) { + this.description = description; + } + + public void markDone() { + this.isDone = true; + } + + public void unmarkDone() { + this.isDone = false; + } + + public int isDoneInt() { + return this.isDone ? 1 : 0; + } + + public String saveToFileFormat() { + return ""; + } + + @Override + public String toString() { + return (this.isDone ? "[X] " : "[ ] ") + this.description; + } + +} \ No newline at end of file diff --git a/src/main/java/faith/model/task/Todo.java b/src/main/java/faith/model/task/Todo.java new file mode 100644 index 0000000000..162bd305c3 --- /dev/null +++ b/src/main/java/faith/model/task/Todo.java @@ -0,0 +1,22 @@ +package faith.model.task; + +/** + * Task with description + */ +public class Todo extends Task { + + + public Todo(String description) { + super(description); + } + + @Override + public String saveToFileFormat() { + return "T | " + this.isDoneInt() + " | " + description; + } + + @Override + public String toString() { + return "[T]" + super.toString(); + } +} \ No newline at end of file diff --git a/src/main/java/faith/ui/DialogBox.java b/src/main/java/faith/ui/DialogBox.java new file mode 100644 index 0000000000..fe60a476b9 --- /dev/null +++ b/src/main/java/faith/ui/DialogBox.java @@ -0,0 +1,60 @@ +package faith.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; + +/** + * Represents a dialog box consisting of an ImageView to represent the speaker's face + * and a label containing text from the speaker. + */ +public class DialogBox extends HBox { + @FXML + private Label dialog; + @FXML + private ImageView displayPicture; + + private DialogBox(String text, Image img) { + try { + FXMLLoader fxmlLoader = new FXMLLoader(MainWindow.class.getResource("/view/DialogBox.fxml")); + fxmlLoader.setController(this); + fxmlLoader.setRoot(this); + fxmlLoader.load(); + } catch (IOException e) { + e.printStackTrace(); + } + + dialog.setText(text); + displayPicture.setImage(img); + } + + /** + * Flips the dialog box such that the ImageView is on the left and text on the right. + */ + private void flip() { + ObservableList tmp = FXCollections.observableArrayList(this.getChildren()); + Collections.reverse(tmp); + getChildren().setAll(tmp); + setAlignment(Pos.TOP_LEFT); + } + + public static DialogBox getUserDialog(String text, Image img) { + return new DialogBox(text, img); + } + + public static DialogBox getFaithDialog(String text, Image img) { + var db = new DialogBox(text, img); + db.flip(); + return db; + } +} \ No newline at end of file diff --git a/src/main/java/faith/ui/MainWindow.java b/src/main/java/faith/ui/MainWindow.java new file mode 100644 index 0000000000..4239c25ecc --- /dev/null +++ b/src/main/java/faith/ui/MainWindow.java @@ -0,0 +1,49 @@ +package faith.ui; + +import faith.Faith; +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; + +public class MainWindow extends AnchorPane { + @FXML + private ScrollPane scrollPane; + @FXML + private VBox dialogContainer; + @FXML + private TextField userInput; + @FXML + private Button sendButton; + + private Faith faith; + + private Image userImage = new Image(this.getClass().getResourceAsStream("/images/DaUser.png")); + private Image faithImage = new Image(this.getClass().getResourceAsStream("/images/chatbot.png")); + + @FXML + public void initialize() { + scrollPane.vvalueProperty().bind(dialogContainer.heightProperty()); + + dialogContainer.getChildren() + .add(DialogBox.getFaithDialog("Hello! I'm Faith\nWhat can I do for you?", faithImage)); + } + + public void setFaith(Faith f) { + faith = f; + } + + @FXML + private void handleUserInput() { + String input = userInput.getText(); + String response = faith.getResponse(input); + dialogContainer.getChildren().addAll( + DialogBox.getUserDialog(input, userImage), + DialogBox.getFaithDialog(response, faithImage) + ); + userInput.clear(); + } +} diff --git a/src/main/resources/images/DaUser.png b/src/main/resources/images/DaUser.png new file mode 100644 index 0000000000..e6bcce0914 Binary files /dev/null and b/src/main/resources/images/DaUser.png differ diff --git a/src/main/resources/images/chatbot.png b/src/main/resources/images/chatbot.png new file mode 100644 index 0000000000..f317232d50 Binary files /dev/null and b/src/main/resources/images/chatbot.png differ diff --git a/src/main/resources/view/DialogBox.fxml b/src/main/resources/view/DialogBox.fxml new file mode 100644 index 0000000000..fe672c90ea --- /dev/null +++ b/src/main/resources/view/DialogBox.fxml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + diff --git a/src/main/resources/view/MainWindow.fxml b/src/main/resources/view/MainWindow.fxml new file mode 100644 index 0000000000..80690a365d --- /dev/null +++ b/src/main/resources/view/MainWindow.fxml @@ -0,0 +1,44 @@ + + + + + + + + + + + +