package savvytodo.model.task;

import java.util.Iterator;
import java.util.List;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import savvytodo.commons.core.UnmodifiableObservableList;
import savvytodo.commons.exceptions.DuplicateDataException;
import savvytodo.commons.util.CollectionUtil;

/**
 * A list of tasks that enforces uniqueness between its elements and does not allow nulls.
 *
 * Supports a minimal set of list operations.
 *
 * @see Task#equals(Object)
 * @see CollectionUtil#elementsAreUnique(Collection)
 */
public class UniqueTaskList implements Iterable<Task> {

    private final ObservableList<Task> internalList = FXCollections.observableArrayList();

    //@@author A0140016B
    /**
     * @return ObservableList<Task> for sorting purpose
     */
    public ObservableList<Task> getInternalList() {
        return internalList;
    }

    /**
     * Returns true if the list contains an equivalent task as the given argument.
     */
    public boolean contains(ReadOnlyTask toCheck) {
        assert toCheck != null;
        return internalList.contains(toCheck);
    }

    /**
     * Adds a task to the list, list is then sorted by the data and time it was added
     *
     * @throws DuplicateTaskException if the task to add is a duplicate of an existing task in the list.
     */
    public void add(Task toAdd) throws DuplicateTaskException {
        assert toAdd != null;
        if (contains(toAdd)) {
            throw new DuplicateTaskException();
        }
        internalList.add(toAdd);
        internalList.sort((ReadOnlyTask task1, ReadOnlyTask task2) -> task1.getTimeStamp().getDateTimeAdded().compareTo(
                task2.getTimeStamp().getDateTimeAdded()));
    }

    /**
     * Updates the task in the list at position {@code index} with {@code editedTask}.
     *
     * @throws DuplicateTaskException if updating the task's details causes the task to be equivalent to
     *      another existing task in the list.
     * @throws IndexOutOfBoundsException if {@code index} < 0 or >= the size of the list.
     */
    public void updateTask(int index, ReadOnlyTask editedTask) throws DuplicateTaskException {
        assert editedTask != null;

        Task taskToUpdate = internalList.get(index);
        if (!taskToUpdate.equals(editedTask) && internalList.contains(editedTask)) {
            throw new DuplicateTaskException();
        }

        taskToUpdate.resetData(editedTask);
        // TODO: The code below is just a workaround to notify observers of the updated task.
        // The right way is to implement observable properties in the Task class.
        // Then, TaskCard should then bind its text labels to those observable properties.
        internalList.set(index, taskToUpdate);
    }

    /**
     * Removes the equivalent task from the list.
     *
     * @throws TaskNotFoundException if no such task could be found in the list.
     */
    public boolean remove(ReadOnlyTask toRemove) throws TaskNotFoundException {
        assert toRemove != null;
        final boolean taskFoundAndDeleted = internalList.remove(toRemove);
        if (!taskFoundAndDeleted) {
            throw new TaskNotFoundException();
        }
        return taskFoundAndDeleted;
    }

    public void setTasks(UniqueTaskList replacement) {
        this.internalList.setAll(replacement.internalList);
    }

    public void setTasks(List<? extends ReadOnlyTask> tasks) throws DuplicateTaskException {
        final UniqueTaskList replacement = new UniqueTaskList();
        for (final ReadOnlyTask task : tasks) {
            replacement.add(new Task(task));
        }
        setTasks(replacement);
    }

    public UnmodifiableObservableList<Task> asObservableList() {
        return new UnmodifiableObservableList<>(internalList);
    }

    @Override
    public Iterator<Task> iterator() {
        return internalList.iterator();
    }

    @Override
    public boolean equals(Object other) {
        return other == this // short circuit if same object
                || (other instanceof UniqueTaskList // instanceof handles nulls
                && this.internalList.equals(
                ((UniqueTaskList) other).internalList));
    }

    @Override
    public int hashCode() {
        return internalList.hashCode();
    }

    /**
     * Signals that an operation would have violated the 'no duplicates' property of the list.
     */
    public static class DuplicateTaskException extends DuplicateDataException {
        protected DuplicateTaskException() {
            super("Operation would result in duplicate tasks");
        }
    }

    /**
     * Signals that an operation targeting a specified task in the list would fail because
     * there is no such matching task in the list.
     */
    public static class TaskNotFoundException extends Exception {}

}

@@ -24,16 +24,45 @@
 .task;%0A%0A
+import java.util.Collection;%0A
 import j
@@ -1531,32 +1531,37 @@
 teTaskException(
+toAdd
 );%0A        %7D%0A   
@@ -1672,32 +1672,49 @@
 1.getTimeStamp()
+%0A                
 .getDateTimeAdde
@@ -1727,33 +1727,16 @@
 mpareTo(
-%0A                
 task2.ge
@@ -2435,32 +2435,42 @@
 teTaskException(
+editedTask
 );%0A        %7D%0A%0A  
@@ -4179,16 +4179,24 @@
         
+        
 && this.
@@ -4215,33 +4215,16 @@
 .equals(
-%0A                
 ((Unique
@@ -4344,32 +4344,57 @@
 hCode();%0A    %7D%0A%0A
+    //@@author A0140036X%0A
     /**%0A     * S
@@ -4560,32 +4560,250 @@
 DataException %7B%0A
+        private final ReadOnlyTask toAdd;%0A%0A        //@@author A01400036X%0A        /** Returns attempted task **/%0A        public ReadOnlyTask getTask() %7B%0A            return toAdd;%0A        %7D%0A%0A        //@@author A0140036X%0A
         protecte
@@ -4827,16 +4827,38 @@
 ception(
+ReadOnlyTask toAddTask
 ) %7B%0A    
@@ -4917,16 +4917,52 @@
 asks%22);%0A
+            this.toAdd = toAddTask;%0A
         
@@ -5193,13 +5193,18 @@
 eption %7B
+%0A    
 %7D%0A%0A%7D%0A

Edit UniqueTaskList codestyle Make assertion error for DuplicateTaskException more informative