package taskDo;

import Parser.ParsedResult;
import commandFactory.CommandAction;
import commandFactory.CommandFactory;
import commandFactory.CommandType;
import commonClasses.Constants;
import commonClasses.StorageList;
import commonClasses.SummaryReport;

public class Executor {

	public Executor() {
		StorageList.getInstance().loadFile();
	}

	public void execute(ParsedResult parsedResult) {		
		CommandFactory commandFactory = new CommandFactory();
		CommandType commandType = parsedResult.getCommandType();

		if (commandType.equals(CommandType.UNDO)) {
			executeUndo(parsedResult);
		}else	if(commandType.equals(CommandType.REDO)){
			executeRedo(parsedResult);
		}else{
			executeCommand(parsedResult, commandFactory, commandType);
		}
		CategoryList.updateCategoryList(StorageList.getInstance().getTaskList());
	}

	private void executeUndo(ParsedResult parsedResult) {
		if(!History.getUndoActionHistory().empty()){
			CommandAction commandAction = History.getUndoActionHistory().pop();
			Task lastTask = History.getUndoTaskHistory().pop();

			History.getRedoActionHistory().push(commandAction);

			parsedResult.setTask(lastTask);
			commandAction.undo(parsedResult);


			CategoryList.updateCategoryList(StorageList.getInstance().getTaskList());
		}else{
			History.getUndoTaskHistory().clear();
			SummaryReport.setFeedBackMsg(Constants.MESSAGE_FAIL_UNDO);
		}
	}

	private void executeRedo(ParsedResult parsedResult) {
		if(!History.getRedoActionHistory().empty()){
			CommandAction commandAction = History.getRedoActionHistory().pop();
			Task lastTask = History.getRedoTaskHistory().pop();

			parsedResult.setTask(lastTask);
			commandAction.execute(parsedResult);
			
			CategoryList.updateCategoryList(StorageList.getInstance().getTaskList());
		}else{
			History.getRedoTaskHistory().clear();
			SummaryReport.setFeedBackMsg(Constants.MESSAGE_FAIL_REDO);
		}
	}

	private void executeCommand(ParsedResult parsedResult,
			CommandFactory commandFactory, CommandType commandType) {
		CommandAction commandAction = commandFactory.getCommandAction(commandType);			
		commandAction.execute(parsedResult);
		if(!commandType.equals(CommandType.DISPLAY)&&!commandType.equals(CommandType.SEARCH)){
			History.getUndoActionHistory().push(commandAction);
			StorageList.getInstance().saveToFile();
		}
	}
}
@@ -740,16 +740,19 @@
 e);%0A%09%09%7D%0A
+%09%09%0A
 %09%09Catego
@@ -819,16 +819,59 @@
 ist());%0A
+%09%09StorageList.getInstance().saveToFile();%09%0A
 %09%7D%0A%0A%09pri
@@ -1227,87 +1227,8 @@
 t);%0A
-%0A%0A%09%09%09CategoryList.updateCategoryList(StorageList.getInstance().getTaskList());%0A
 %09%09%7De
@@ -1651,89 +1651,8 @@
 t);%0A
-%09%09%09%0A%09%09%09CategoryList.updateCategoryList(StorageList.getInstance().getTaskList());%0A
 %09%09%7De
@@ -2093,16 +2093,16 @@
 ARCH))%7B%0A
+
 %09%09%09Histo
@@ -2152,51 +2152,8 @@
 n);%0A
-%09%09%09StorageList.getInstance().saveToFile();%0A
 %09%09%7D%0A

fix bug for save undo/redo