package seedu.todo.controllers;

import java.util.HashMap;
import java.util.Map;

import seedu.todo.commons.exceptions.UnmatchedQuotesException;
import seedu.todo.models.TodoListDB;
import seedu.todo.ui.UiManager;
import seedu.todo.ui.views.IndexView;

public class UndoController implements Controller {
    
    private static final String MESSAGE_SUCCESS = "Successfully undid last command!\nTo redo, type \"redo\".";
    private static final String MESSAGE_FAILURE = "There is no command to undo!";

    @Override
    public float inputConfidence(String input) {
        return input.startsWith("undo") ? 1 : 0;
    }
    
    private static Map<String, String[]> getTokenDefinitions() {
        Map<String, String[]> tokenDefinitions = new HashMap<String, String[]>();
        tokenDefinitions.put("default", new String[] {"undo"});
        return tokenDefinitions;
    }

    @Override
    public void process(String input) {
        
        Map<String, String[]> parsedResult;
        try {
            parsedResult = Tokenizer.tokenize(getTokenDefinitions(), input);            
        } catch (UnmatchedQuotesException e) {
            System.out.println("Unmatched quote!");
            return;
        }
        
        int numUndo = 1;
        if (parsedResult.get("default") != null) {
            numUndo = Integer.parseInt(parsedResult.get("default")[1]);
        }   
        
        TodoListDB db = TodoListDB.getInstance();
        if (!db.undo()) {
            UiManager.updateConsoleMessage(MESSAGE_FAILURE);
            return;
        }
        db = TodoListDB.getInstance();
        
        // Render
        IndexView view = UiManager.loadView(IndexView.class);
        view.tasks = db.getAllTasks();
        view.events = db.getAllEvents();
        UiManager.renderView(view);
        
        // Update console message
        UiManager.updateConsoleMessage(MESSAGE_SUCCESS);
    }
}

@@ -1381,32 +1381,116 @@
   %7D   %0A        %0A
+        // We don't really have a nice way to support SQL transactions, so yeah %3E_%3C%0A
         TodoList
@@ -1515,32 +1515,80 @@
 .getInstance();%0A
+        for (int i = 0; i %3C numUndo; i++) %7B%0A    
         if (!db.
@@ -1593,24 +1593,28 @@
 b.undo()) %7B%0A
+    
             
@@ -1670,32 +1670,36 @@
             
+    
 return;%0A
         %7D%0A  
@@ -1678,32 +1678,46 @@
         return;%0A
+            %7D%0A
         %7D%0A      

Undo n times.