//   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.plugin.exports.commands;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import de.ugoe.cs.autoquest.CommandHelpers;
import de.ugoe.cs.autoquest.exports.tasktrees.ObjectFactory;
import de.ugoe.cs.autoquest.exports.tasktrees.TaskModel;
import de.ugoe.cs.autoquest.plugin.exports.tasktree.CTTExportUtils;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IEventTask;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IMarkingTemporalRelationship;
import de.ugoe.cs.autoquest.tasktrees.treeifc.IStructuringTemporalRelationship;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITask;
import de.ugoe.cs.autoquest.tasktrees.treeifc.ITaskModel;
import de.ugoe.cs.util.console.Command;
import de.ugoe.cs.util.console.Console;
import de.ugoe.cs.util.console.GlobalDataContainer;

/**
 * <p>
 * TODO comment
 * </p>
 * 
 * @author Patrick Harms
 * @version 1.0
 */
public class CMDexportToCTT implements Command {

    /** */
    private static final ObjectFactory objFact = new ObjectFactory();
    
    /*
     * (non-Javadoc)
     * 
     * @see de.ugoe.cs.util.console.Command#run(java.util.List)
     */
    @Override
    public void run(List<Object> parameters) {
        String dirname = null;
        String tasktreename = null;

        try {
            for (int i = 0; i < parameters.size(); i++) {
                String param = (String) parameters.get(i);
                if (tasktreename == null) {
                    tasktreename = param;
                }
                else if (dirname == null) {
                    dirname = param;
                }
            }
        }
        catch (Exception e) {
            throw new IllegalArgumentException("illegal parameters provided: " + e);
        }

        if (tasktreename == null) {
            tasktreename = "tasktree";
        }

        if (dirname == null) {
            dirname = tasktreename + "_ctte";
        }

        Object taskTreeObj = GlobalDataContainer.getInstance().getData(tasktreename);
        
        if (taskTreeObj == null) {
            CommandHelpers.objectNotFoundMessage(tasktreename);
            return;
        }
        else if (!(taskTreeObj instanceof ITaskModel)) {
            CommandHelpers.objectNotType(tasktreename, "task model");
            return;
        }
        
        File directory = new File(dirname);
        
        if (directory.exists()) {
            Console.printerrln("The directory " + directory.getAbsolutePath() + " already exists." +
                               " Please delete it and try again.");
            return;
        }
        else {
            if (!directory.mkdirs()) {
                Console.printerrln("Could not create directory " + directory.getAbsolutePath() +
                                   ". Please try another one.");
                return;
            }
        }
        
        Console.println("exporting " + tasktreename + " to directory " +
                        directory.getAbsolutePath());
        
        List<TaskModel> models = map((ITaskModel) taskTreeObj);
        
        Console.println("exporting " + models.size() + " root tasks " +
                        directory.getAbsolutePath());

        for (TaskModel model : models) {
            File file = new File(directory, model.getNameTaskModelID() + "_ctte.xml");
            CTTExportUtils.writeToFile(model, file);
        }
    }

    /**
     *
     */
    private List<TaskModel> map(ITaskModel taskModel) {
        List<ITask> roots = getRoots(taskModel.getTasks());
        List<TaskModel> result = new ArrayList<>(roots.size());
        
        for (ITask task : roots) {
            TaskModel cttModel = objFact.createTaskModel();
            cttModel.setTask(CTTExportUtils.map(task, false, false, null));
            cttModel.setNameTaskModelID(Integer.toString(task.getId()));
            result.add(cttModel);
        }
        
        return result;
    }

    /**
     *
     */
    private List<ITask> getRoots(Collection<ITask> tasks) {
        Set<ITask> children = new HashSet<>(tasks.size());
        
        for (ITask parent : tasks) {
            if (parent instanceof IMarkingTemporalRelationship) {
                children.add(((IMarkingTemporalRelationship) parent).getMarkedTask());
            }
            else if (parent instanceof IStructuringTemporalRelationship) {
                for (ITask child : ((IStructuringTemporalRelationship) parent).getChildren()) {
                    children.add(child);
                }
            }
        }
        
        List<ITask> roots = new ArrayList<>(tasks.size() - children.size());
        
        for (ITask candidate : tasks) {
            if ((!(candidate instanceof IEventTask)) && (!children.contains(candidate))) {
                roots.add(candidate);
            }
        }
        
        return roots;
    }

    /*
     * (non-Javadoc)
     * 
     * @see de.ugoe.cs.util.console.Command#help()
     */
    @Override
    public String help() {
        return "exportToCTT [<tasktreename>] [<filename>]";
    }

}
