//   Copyright 2012 Georg-August-Universität Göttingen, Germany
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package de.ugoe.cs.autoquest.tasktrees.treeimpl;

import java.util.List;

import de.ugoe.cs.autoquest.tasktrees.treeifc.IIteration;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IIterationInstance;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IMarkingTemporalRelationship;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IOptional;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IOptionalInstance;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ISelection;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ISelectionInstance;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ISequence;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ISequenceInstance;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IStructuringTemporalRelationship;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITask;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskBuilder;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskInstance;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskInstanceList;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IUserSession;

/**
 * <p>
 * this is the default implementation of the interface {@link ITaskBuilder}. It
 * does not do anything fancy except implementing the interface. In some situations, it performs
 * a check if the model or instances to be created a valid. However, this can not be done
 * in any situation of the creation process.
 * </p>
 * 
 * @author Patrick Harms
 */
public class TaskBuilder implements ITaskBuilder {

    /* (non-Javadoc)
     * @see ITaskBuilder#addChild(ISequenceInstance, ITaskInstance)
     */
    @Override
    public void addChild(ISequenceInstance instance, ITaskInstance child)
        throws IllegalArgumentException
    {
        if (!(instance instanceof SequenceInstance)) {
            throw new IllegalArgumentException
                ("illegal type of sequence instance provided: " + instance.getClass());
        }

        if (!(child instanceof TaskInstance)) {
            throw new IllegalArgumentException
                ("illegal type of task instance provided: " + child.getClass());
        }
        
        SequenceInstance seqInstance = (SequenceInstance) instance;
        
        // check if new child instance matches the model, if this can be checked
        IStructuringTemporalRelationship parentTask =
            (IStructuringTemporalRelationship) instance.getTask();
        
        if (((parentTask.getChildren() != null) && (parentTask.getChildren().size() > 0)) &&
            ((parentTask.getChildren().size() <= seqInstance.size()) ||
             (!parentTask.getChildren().get(seqInstance.size()).equals(child.getTask()))))
        {
            throw new IllegalArgumentException
                ("the task of the child instance to be added does not belong to the children " +
                 "of the task of the parent instance");
        }

        seqInstance.addChild(child);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#addChild(ISequenceInstance, int, ITaskInstance)
     */
    public void addChild(ISequenceInstance instance, int index, ITaskInstance child)
        throws IllegalArgumentException
    {
        if (!(instance instanceof SequenceInstance)) {
            throw new IllegalArgumentException
                ("illegal type of sequence instance provided: " + instance.getClass());
        }

        if (!(child instanceof TaskInstance)) {
            throw new IllegalArgumentException
                ("illegal type of task instance provided: " + child.getClass());
        }
        
        SequenceInstance seqInstance = (SequenceInstance) instance;
        
        // check if new child instance matches the model, if this can be checked
        IStructuringTemporalRelationship parentTask =
            (IStructuringTemporalRelationship) instance.getTask();
        
        if (((parentTask.getChildren() != null) && (parentTask.getChildren().size() > 0)) &&
            ((parentTask.getChildren().size() <= index) ||
             (!parentTask.getChildren().get(index).equals(child.getTask()))))
        {
            throw new IllegalArgumentException
                ("the task of the child instance to be added does not belong to the children " +
                 "of the task of the parent instance");
        }
        
        seqInstance.addChild(index, child);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#addChild(IIterationInstance, ITaskInstance)
     */
    @Override
    public void addChild(IIterationInstance instance, ITaskInstance child)
        throws IllegalArgumentException
    {
        if (!(instance instanceof IterationInstance)) {
            throw new IllegalArgumentException
                ("illegal type of iteration instance provided: " + instance.getClass());
        }

        if (!(child instanceof TaskInstance)) {
            throw new IllegalArgumentException
                ("illegal type of task instance provided: " + child.getClass());
        }
        
        // check if new child instance matches the model, if this can be checked
        IMarkingTemporalRelationship parentTask =
            (IMarkingTemporalRelationship) instance.getTask();
                
        boolean foundChildTask = parentTask.getMarkedTask() != null ?
            parentTask.getMarkedTask().equals(child.getTask()) : true;
                
        if (!foundChildTask) {
            throw new IllegalArgumentException
                ("the task of the child instance does not match the model of the task of the " +
                 "iteration instance: " + parentTask.getMarkedTask() + " <> " + child.getTask());
        }

        ((IterationInstance) instance).addChild(child);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#addChild(IIterationInstance, int, ITaskInstance)
     */
    public void addChild(IIterationInstance instance, int index, ITaskInstance child)
        throws IllegalArgumentException
    {
        if (!(instance instanceof IterationInstance)) {
            throw new IllegalArgumentException
                ("illegal type of iteration instance provided: " + instance.getClass());
        }

        if (!(child instanceof TaskInstance)) {
            throw new IllegalArgumentException
                ("illegal type of task instance provided: " + child.getClass());
        }
        
        // check if new child instance matches the model, if this can be checked
        IMarkingTemporalRelationship parentTask =
            (IMarkingTemporalRelationship) instance.getTask();
                
        boolean foundChildTask = parentTask.getMarkedTask() != null ?
            parentTask.getMarkedTask().equals(child.getTask()) : true;
                
        if (!foundChildTask) {
            throw new IllegalArgumentException
                ("the task of the child instance does not match the model of the task of the " +
                 "iteration instance: " + parentTask.getMarkedTask() + " <> " + child.getTask());
        }

        ((IterationInstance) instance).addChild(index, child);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#setChild(ISelectionInstance, ITaskInstance)
     */
    @Override
    public void setChild(ISelectionInstance instance, ITaskInstance child)
        throws IllegalArgumentException
    {
        if (!(instance instanceof SelectionInstance)) {
            throw new IllegalArgumentException
                ("illegal type of selection instance provided: " + instance.getClass());
        }

        if (!(child instanceof TaskInstance)) {
            throw new IllegalArgumentException("illegal type of task instance provided: " +
                                               (child == null ? null : child.getClass()));
        }
        
        // check if new child instance matches the model, if this can be checked
        IStructuringTemporalRelationship parentTask =
            (IStructuringTemporalRelationship) instance.getTask();
        
        boolean foundChildTask = false;
        for (ITask parentTaskChild : parentTask.getChildren()) {
            if (parentTaskChild.equals(child.getTask())) {
                foundChildTask = true;
                break;
            }
        }
            
        if (!foundChildTask) {
            throw new IllegalArgumentException
                ("the task of the child instance to be added does not belong to the children " +
                 "of the selection task model of the parent instance");
        }

        ((SelectionInstance) instance).setChild(child);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#setChild(IOptionalInstance, ITaskInstance)
     */
    @Override
    public void setChild(IOptionalInstance instance, ITaskInstance child)
        throws IllegalArgumentException
    {
        if (!(instance instanceof OptionalInstance)) {
            throw new IllegalArgumentException
                ("illegal type of optional instance provided: " + instance.getClass());
        }

        if (!(child instanceof TaskInstance)) {
            throw new IllegalArgumentException
                ("illegal type of task instance provided: " + child.getClass());
        }
        
        // check if new child instance matches the model, if this can be checked
        IMarkingTemporalRelationship parentTask =
            (IMarkingTemporalRelationship) instance.getTask();
            
        boolean foundChildTask = parentTask.getMarkedTask() != null ?
            parentTask.getMarkedTask().equals(child.getTask()) : true;
            
        if (!foundChildTask) {
            throw new IllegalArgumentException
                ("the task of the child instance does not match the model of the task of the " +
                 "optional instance: " + parentTask.getMarkedTask() + " <> " + child.getTask());
        }

        ((OptionalInstance) instance).setChild(child);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#addExecutedTask(IUserSession, ITaskInstance)
     */
    @Override
    public void addExecutedTask(IUserSession session, ITaskInstance taskInstance) {
        if (!(session instanceof UserSession)) {
            throw new IllegalArgumentException
                ("illegal type of session provided: " + session.getClass());
        }

        if (!(taskInstance instanceof TaskInstance)) {
            throw new IllegalArgumentException
                ("illegal type of task instance provided: " + taskInstance.getClass());
        }
        
        ((UserSession) session).addExecutedTask(taskInstance);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#addExecutedTask(IUserSession, int, ITaskInstance)
     */
    public void addExecutedTask(IUserSession session, int index, ITaskInstance taskInstance) {
        if (!(session instanceof UserSession)) {
            throw new IllegalArgumentException
                ("illegal type of session provided: " + session.getClass());
        }

        if (!(taskInstance instanceof TaskInstance)) {
            throw new IllegalArgumentException
                ("illegal type of task instance provided: " + taskInstance.getClass());
        }
        
        ((UserSession) session).addExecutedTask(index, taskInstance);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#addTaskInstance(ITaskInstanceList, ITaskInstance)
     */
    @Override
    public void addTaskInstance(ITaskInstanceList taskInstanceList, ITaskInstance taskInstance) {
        if (taskInstanceList instanceof SequenceInstance) {
            addChild((SequenceInstance) taskInstanceList, taskInstance);
        }
        else if (taskInstanceList instanceof IterationInstance) {
            addChild((IterationInstance) taskInstanceList, taskInstance);
        }
        else if (taskInstanceList instanceof UserSession) {
            addExecutedTask((UserSession) taskInstanceList, taskInstance);
        }
        else {
            throw new IllegalArgumentException
                ("illegal type of task instance list provided: " + taskInstanceList.getClass());
        }
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#addTaskInstance(ITaskInstanceList, int, ITaskInstance)
     */
    @Override
    public void addTaskInstance(ITaskInstanceList taskInstanceList,
                                int               index,
                                ITaskInstance     taskInstance)
    {
        if (taskInstanceList instanceof SequenceInstance) {
            addChild((SequenceInstance) taskInstanceList, index, taskInstance);
        }
        else if (taskInstanceList instanceof IterationInstance) {
            addChild((IterationInstance) taskInstanceList, index, taskInstance);
        }
        else if (taskInstanceList instanceof UserSession) {
            addExecutedTask((UserSession) taskInstanceList, index, taskInstance);
        }
        else {
            throw new IllegalArgumentException
                ("illegal type of task instance list provided: " + taskInstanceList.getClass());
        }
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#setTaskInstance(ITaskInstanceList, int, ITaskInstance)
     */
    @Override
    public void setTaskInstance(ITaskInstanceList taskInstanceList,
                                int               index,
                                ITaskInstance     taskInstance)
    {
        removeTaskInstance(taskInstanceList, index);
        addTaskInstance(taskInstanceList, index, taskInstance);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#setTask(ITaskInstance, ITask)
     */
    @Override
    public void setTask(ITaskInstance taskInstance, ITask task) {
        if (!(taskInstance instanceof TaskInstance)) {
            throw new IllegalArgumentException
                ("illegal type of task instance provided: " + taskInstance.getClass());
        }
        if (!(task instanceof Task)) {
            throw new IllegalArgumentException("illegal type of task provided: " + task.getClass());
        }
        
        if (((TaskInstance) taskInstance).getTask() instanceof Task) {
            ((Task) ((TaskInstance) taskInstance).getTask()).removeInstance(taskInstance);
        }
        ((TaskInstance) taskInstance).setTask(task);
        
        ((Task) task).addInstance(taskInstance);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#addChild(ISequence, ITask)
     */
    @Override
    public void addChild(ISequence parent, ITask child) {
        if (!(parent instanceof Sequence)) {
            throw new IllegalArgumentException
                ("illegal type of sequence provided: " + parent.getClass());
        }

        addChildInternal((Sequence) parent, -1, child);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#addChild(ISequence, int, ITask)
     */
    @Override
    public void addChild(ISequence parent, int index, ITask child) {
        if (!(parent instanceof Sequence)) {
            throw new IllegalArgumentException
                ("illegal type of sequence provided: " + parent.getClass());
        }

        addChildInternal((Sequence) parent, index, child);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#setChild(ISequence, int, ITask)
     */
    @Override
    public void setChild(ISequence parent, int index, ITask child) {
        if (!(parent instanceof Sequence)) {
            throw new IllegalArgumentException
                ("illegal type of sequence provided: " + parent.getClass());
        }

        ((Sequence) parent).removeChild(index);
        addChildInternal((Sequence) parent, index, child);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#addChild(ISelection, ITask)
     */
    @Override
    public void addChild(ISelection parent, ITask child) {
        if (!(parent instanceof Selection)) {
            throw new IllegalArgumentException
                ("illegal type of selection provided: " + parent.getClass());
        }

        addChildInternal((Selection) parent, -1, child);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#setMarkedTask(IIteration, ITask)
     */
    @Override
    public void setMarkedTask(IIteration iteration, ITask newChild) {
        if (!(iteration instanceof Iteration)) {
            throw new IllegalArgumentException
                ("illegal type of iteration provided: " + iteration.getClass());
        }

        if (!(newChild instanceof Task)) {
            throw new IllegalArgumentException
                ("illegal type of task provided: " + newChild.getClass());
        }

        ((Iteration) iteration).setMarkedTask(newChild);
    }

    /* (non-Javadoc)
     * @see ITaskTreeBuilder#setChild(IOptional, ITaskTreeNode)
     */
    @Override
    public void setMarkedTask(IOptional optional, ITask newChild) {
        if (!(optional instanceof Optional)) {
            throw new IllegalArgumentException
                ("illegal type of optional provided: " + optional.getClass());
        }

        if (!(newChild instanceof Task)) {
            throw new IllegalArgumentException
                ("illegal type of task provided: " + newChild.getClass());
        }

        ((Optional) optional).setMarkedTask(newChild);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#removeChild(ISequence, int)
     */
    @Override
    public void removeChild(ISequence parent, int index) {
        if (!(parent instanceof Sequence)) {
            throw new IllegalArgumentException
                ("illegal type of sequence provided: " + parent.getClass());
        }

        ((Sequence) parent).removeChild(index);
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#removeChild(ISelection, ITask)
     */
    @Override
    public void removeChild(ISelection parent, ITask child) {
        if (!(parent instanceof Selection)) {
            throw new IllegalArgumentException
                ("illegal type of selection provided: " + parent.getClass());
        }

        List<ITask> children = parent.getChildren();
        
        for (int i = 0; i < children.size(); i++) {
            if ((children.get(i) == child) ||
                ((children.get(i) != null) && (children.get(i).equals(child))))
            {
                ((Selection) parent).removeChild(i);
                break;
            }
        }
    }

    /* (non-Javadoc)
     * @see ITaskBuilder#removeTaskInstance(ITaskInstanceList, int)
     */
    @Override
    public void removeTaskInstance(ITaskInstanceList taskInstanceList, int index) {
        if (taskInstanceList instanceof SequenceInstance) {
            ((SequenceInstance) taskInstanceList).removeChild(index);
        }
        else if (taskInstanceList instanceof IterationInstance) {
            ((IterationInstance) taskInstanceList).removeChild(index);
        }
        else if (taskInstanceList instanceof UserSession) {
            ((UserSession) taskInstanceList).removeExecutedTask(index);
        }
        else {
            throw new IllegalArgumentException
                ("illegal type of task instance list provided: " + taskInstanceList.getClass());
        }
    }

    /* (non-Javadoc)
     * @see ITaskTreeBuilder#replaceChild(ISelection, ITaskTreeNode, ITaskTreeNode)
     */
    @Override
    public void replaceChild(ISelection parent, ITask oldChild, ITask newChild) {
        if (!(parent instanceof Selection)) {
            throw new IllegalArgumentException
                ("illegal type of selection provided: " + parent.getClass());
        }

        List<ITask> children = parent.getChildren();
        
        for (int i = 0; i < children.size(); i++) {
            if ((children.get(i) == oldChild) ||
                ((children.get(i) != null) && (children.get(i).equals(oldChild))))
            {
                ((Selection) parent).removeChild(i);
                ((Selection) parent).addChild(i, newChild);
                break;
            }
        }
    }

    /**
     * <p>
     * internal convenience method for adding children to a structuring temporal relationship
     * including a check for the child type.
     * </p>
     */
    private void addChildInternal(StructuringTemporalRelationship parent, int index, ITask child) {
        if (!(child instanceof Task)) {
            throw new IllegalArgumentException
                ("illegal type of task provided: " + child.getClass());
        }

        if (index > -1) {
            parent.addChild(index, child);
        }
        else {
            parent.addChild(child);
        }
    }

}
