package net.sourceforge.ganttproject.action;

import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.KeyStroke;

import net.sourceforge.ganttproject.GanttProject;
import net.sourceforge.ganttproject.GanttTask;
import net.sourceforge.ganttproject.IGanttProject;
import net.sourceforge.ganttproject.action.task.TaskActionBase;
import net.sourceforge.ganttproject.gui.UIFacade;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.task.Task;
import net.sourceforge.ganttproject.task.TaskMutator;
import net.sourceforge.ganttproject.task.TaskSelectionManager;

public class NewTaskAction extends TaskActionBase {
    private final boolean myCreateSubtaskFlag;

	public NewTaskAction(IGanttProject project, TaskSelectionManager selectionManager, UIFacade uiFacade, boolean createSubtask) {
    	super(project.getTaskManager(), selectionManager, uiFacade);
    	myCreateSubtaskFlag = createSubtask;
        putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_T,
                Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()));
    }

	protected String getLocalizedName() {
		return getI18n("newTask");
	}

	public void languageChanged(GanttLanguage.Event event) {
        setText(event.getLanguage());
    }

    private void setText(GanttLanguage language) {
        this.putValue(AbstractAction.NAME, GanttProject.correctLabel(language
                .getText("newTask")));
    }

	@Override
	protected boolean isEnabled(List selection) {
		return selection.size()<=1;
	}

	@Override
	protected void run(final List<Task> selection) throws Exception {
        getUIFacade().getUndoManager().undoableEdit("New Task", new Runnable() {
            public void run() {
            	//final GanttCalendar startDate = new GanttCalendar(getUIFacade().getGanttChart().getStartDate());
                GanttTask task = getTaskManager().createTask();
                //getTaskManager().registerTask(task);
                task.setName(task.getName()+"_"+task.getTaskID());
                TaskMutator mutator = task.createMutator();
                mutator.createFixedDurationTimeInterval().setStartDate(getUIFacade().getGanttChart().getStartDate());
                mutator.commit();
                if (myCreateSubtaskFlag){
                	Task parent = !selection.isEmpty() ? selection.get(0) : getTaskManager().getRootTask();
                   	getTaskManager().getTaskHierarchy().move(task, parent);
                }
                else {
                	Task anchor = selection.isEmpty() ? null : selection.get(0);
                	Task parent = anchor==null ? getTaskManager().getRootTask() : getTaskManager().getTaskHierarchy().getContainer(anchor);
                	if (anchor==null) {
                		getTaskManager().getTaskHierarchy().move(task, parent);
                	}
                	else {
                		int position = -1;
                		Task[] currentlyNested = getTaskManager().getTaskHierarchy().getNestedTasks(parent);
                		for (int i=0; i<currentlyNested.length; i++) {
                			if (currentlyNested[i]==anchor) {
                				position = i+1;
                				break;
                			}
                		}
                		assert position>=0;
                		getTaskManager().getTaskHierarchy().move(task, parent, position);
                	}
                }
                /* Register task after adding it to HierarchyFacade so taskAdded Event is generated after all addition operations */
                getTaskManager().registerTask(task);
               	getSelectionManager().clear();
               	getSelectionManager().addTask(task);
               	getUIFacade().getGanttChart().editTaskAsNew(task);
            }
        });
	}

	@Override
	protected String getIconFilePrefix() {
		return "insert_";
	}

}
