package net.sourceforge.ganttproject.task.dependency.constraint;

import java.util.Date;

import net.sourceforge.ganttproject.GanttCalendar;
import net.sourceforge.ganttproject.GanttTaskRelationship;
import net.sourceforge.ganttproject.language.GanttLanguage;
import net.sourceforge.ganttproject.task.Task;
import net.sourceforge.ganttproject.task.TaskActivity;
import net.sourceforge.ganttproject.task.TaskLength;
import net.sourceforge.ganttproject.task.dependency.TaskDependency;
import net.sourceforge.ganttproject.task.dependency.TaskDependencyConstraint;
import net.sourceforge.ganttproject.task.dependency.TaskDependency.ActivityBinding;

/**
 * Dependant task starts not earlier than dependee finishes Created by IntelliJ
 * IDEA. User: bard
 */
public class FinishStartConstraintImpl extends ConstraintImpl implements
        TaskDependencyConstraint {
    public FinishStartConstraintImpl() {
        super(GanttTaskRelationship.FS, GanttLanguage.getInstance().getText(
                "finishstart"));
    }

    public TaskDependencyConstraint.Collision getCollision() {
        TaskDependencyConstraint.Collision result = null;
        Task dependee = getDependency().getDependee();
        Task dependant = getDependency().getDependant();
        Date dependeeEnd = dependee.getEnd().getTime();
        Date dependantStart = dependant.getStart().getTime();

        TaskLength lag = getDependency().getLag();
        Date comparisonDate = lag.getValue()==0 ? 
        		dependantStart : getTaskManager().shift(dependantStart, lag);

        boolean isActive = getDependency().getHardness()==TaskDependency.Hardness.RUBBER ? dependeeEnd
                .compareTo(comparisonDate) > 0 : dependeeEnd
                .compareTo(comparisonDate) != 0;
        // new Exception("[FinishStartConstraint] isActive="+isActive+"
        // dependdee="+dependee+" end="+dependeeEnd+"
        // start="+dependantStart).printStackTrace();
        GanttCalendar acceptableStart = isActive ? 
        		new GanttCalendar(getTaskManager().shift(dependeeEnd, lag)) : dependee.getEnd();
        result = new TaskDependencyConstraint.DefaultCollision(acceptableStart,
                TaskDependencyConstraint.Collision.START_LATER_VARIATION,
                isActive);
        return result;
    }

    public ActivityBinding getActivityBinding() {
        TaskActivity[] dependantActivities = getDependency().getDependant()
                .getActivities();
        TaskActivity[] dependeeActivities = getDependency().getDependee()
                .getActivities();
        TaskActivity theDependant = dependantActivities[0];
        TaskActivity theDependee = dependeeActivities[dependeeActivities.length - 1];
        return new DependencyActivityBindingImpl(theDependant, theDependee,
                new Date[] { theDependant.getStart(), theDependee.getEnd() });
    }

}
