package seedu.ezdo.model;

import java.util.Set;
import java.util.logging.Logger;

import javafx.collections.transformation.FilteredList;
import seedu.ezdo.commons.core.ComponentManager;
import seedu.ezdo.commons.core.LogsCenter;
import seedu.ezdo.commons.core.UnmodifiableObservableList;
import seedu.ezdo.commons.events.model.EzDoChangedEvent;
import seedu.ezdo.commons.util.CollectionUtil;
import seedu.ezdo.commons.util.StringUtil;
import seedu.ezdo.model.todo.ReadOnlyTask;
import seedu.ezdo.model.todo.Task;
import seedu.ezdo.model.todo.UniqueTaskList;
import seedu.ezdo.model.todo.UniqueTaskList.TaskNotFoundException;

/**
 * Represents the in-memory model of the ezDo data.
 * All changes to any model should be synchronized.
 */
public class ModelManager extends ComponentManager implements Model {
    private static final Logger logger = LogsCenter.getLogger(ModelManager.class);

    private final EzDo ezDo;
    private final FilteredList<ReadOnlyTask> filteredTasks;

    /**
     * Initializes a ModelManager with the given ezDo and userPrefs.
     */
    public ModelManager(ReadOnlyEzDo ezDo, UserPrefs userPrefs) {
        super();
        assert !CollectionUtil.isAnyNull(ezDo, userPrefs);

        logger.fine("Initializing with ezDo: " + ezDo + " and user prefs " + userPrefs);

        this.ezDo = new EzDo(ezDo);
        filteredTasks = new FilteredList<>(this.ezDo.getTaskList());
    }

    public ModelManager() {
        this(new EzDo(), new UserPrefs());
    }

    @Override
    public void resetData(ReadOnlyEzDo newData) {
        ezDo.resetData(newData);
        indicateEzDoChanged();
    }

    @Override
    public ReadOnlyEzDo getEzDo() {
        return ezDo;
    }

    /** Raises an event to indicate the model has changed */
    private void indicateEzDoChanged() {
        raise(new EzDoChangedEvent(ezDo));
    }

    @Override
    public synchronized void killTask(ReadOnlyTask target) throws TaskNotFoundException {
        ezDo.removeTask(target);
        indicateEzDoChanged();
    }

    @Override
    public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException {
        ezDo.addTask(task);
        updateFilteredListToShowAll();
        indicateEzDoChanged();
    }
    
    @Override
    public synchronized void doneTask(ReadOnlyTask task) {
        ezDo.doneTask(task);
        updateFilteredListToShowAll();
        indicateEzDoChanged();
    }

    @Override
    public void updateTask(int filteredTaskListIndex, ReadOnlyTask editedTask)
            throws UniqueTaskList.DuplicateTaskException {
        assert editedTask != null;

        int ezDoIndex = filteredTasks.getSourceIndex(filteredTaskListIndex);
        ezDo.updateTask(ezDoIndex, editedTask);
        indicateEzDoChanged();
    }

    //=========== Filtered Task List Accessors =============================================================

    @Override
    public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() {
        return new UnmodifiableObservableList<>(filteredTasks);
    }

    @Override
    public void updateFilteredListToShowAll() {
        filteredTasks.setPredicate(null);
    }

    @Override
    public void updateFilteredTaskList(Set<String> keywords) {
        updateFilteredTaskList(new PredicateExpression(new NameQualifier(keywords)));
    }

    private void updateFilteredTaskList(Expression expression) {
        filteredTasks.setPredicate(expression::satisfies);
    }

    //========== Inner classes/interfaces used for filtering =================================================

    interface Expression {
        boolean satisfies(ReadOnlyTask task);
        String toString();
    }

    private class PredicateExpression implements Expression {

        private final Qualifier qualifier;

        PredicateExpression(Qualifier qualifier) {
            this.qualifier = qualifier;
        }

        @Override
        public boolean satisfies(ReadOnlyTask task) {
            return qualifier.run(task);
        }

        @Override
        public String toString() {
            return qualifier.toString();
        }
    }

    interface Qualifier {
        boolean run(ReadOnlyTask task);
        String toString();
    }

    private class NameQualifier implements Qualifier {
        private Set<String> nameKeyWords;

        NameQualifier(Set<String> nameKeyWords) {
            this.nameKeyWords = nameKeyWords;
        }

        @Override
        public boolean run(ReadOnlyTask task) {
            return nameKeyWords.stream()
                    .filter(keyword -> StringUtil.containsWordIgnoreCase(task.getName().fullName, keyword))
                    .findAny()
                    .isPresent();
        }

        @Override
        public String toString() {
            return "name=" + String.join(", ", nameKeyWords);
        }
    }

}

@@ -2294,34 +2294,59 @@
 oneTask(
-ReadOnly
+Task Done
 Task
+)
  t
-ask)
+hrows TaskNotFoundException
  %7B%0A     
@@ -2358,25 +2358,29 @@
 Do.doneTask(
-t
+DoneT
 ask);%0A      
@@ -2391,37 +2391,32 @@
 dateFiltered
+Done
 List
-ToShowAll
 ();%0A        
@@ -2901,25 +2901,29 @@
 ===========%0A
+    
 %0A
-
     @Overrid
@@ -2995,24 +2995,32 @@
 TaskList() %7B
+        
 %0A        ret
@@ -3141,33 +3141,39 @@
 All() %7B%0A        
-f
+updateF
 ilteredTasks.set
@@ -3171,27 +3171,60 @@
 Task
-s.setPredicate(null
+List(new PredicateExpression(new notDoneQualifier())
 );%0A 
@@ -3390,33 +3390,169 @@
 words)));%0A    %7D%0A
+    %0A    public void updateFilteredDoneList() %7B%0A        updateFilteredTaskList(new PredicateExpression(new DoneQualifier()));%0A    %7D%0A    
 %0A
-
     private void
@@ -4418,32 +4418,735 @@
 oString();%0A    %7D
+%0A    %0A    private class DoneQualifier implements Qualifier %7B%0A        %0A        DoneQualifier() %7B%0A            %0A        %7D%0A        %0A        @Override%0A        public boolean run(ReadOnlyTask task) %7B%0A            return task.getDone();%0A        %7D%0A        %0A        @Override%0A        public String toString() %7B%0A            return %22%22;%0A        %7D%0A        %0A    %7D%0A    %0A    private class notDoneQualifier implements Qualifier %7B%0A        %0A        notDoneQualifier() %7B%0A            %0A        %7D%0A        %0A        @Override%0A        public boolean run(ReadOnlyTask task) %7B%0A            return !task.getDone();%0A        %7D%0A        %0A        @Override%0A        public String toString() %7B%0A            return %22%22;%0A        %7D%0A        %0A    %7D
 %0A%0A    private cl
@@ -5582,16 +5582,16 @@
 ndAny()%0A
-
         
@@ -5614,16 +5614,55 @@
 resent()
+%0A                    && !task.getDone()
 ;%0A      

Update ModelManager to use filteredList to separate done and undone tasks