package de.renew.lola2.commands;

import java.io.PrintStream;

import CH.ifa.draw.DrawPlugin;
import CH.ifa.draw.application.DrawApplication;
import CH.ifa.draw.figures.TextFigure;
import CH.ifa.draw.util.Command;
import de.renew.draw.storables.ontology.Drawing;
import de.renew.draw.storables.ontology.Figure;
import de.renew.draw.storables.ontology.FigureEnumeration;
import de.renew.gui.CPNDrawing;
import de.renew.lola2.LolaTask;
import de.renew.lola2.analysis.LolaAnalyzer;
import de.renew.plugin.command.CLCommand;


/**
 * Checks a selected verification request with Lola and colors the
 * TextFigure of the request depending on the result.
 *
 * @author hewelt
 *
 */
public class CheckAllTasksCommand extends Command implements CLCommand {
    private String _lolaPath;

    /**
     * Creates a new command to check all tasks in the current drawing.
     *
     * @param name the name of the command
     * @param path the path to the Lola executable
     */
    public CheckAllTasksCommand(String name, String path) {
        super(name);
        this._lolaPath = path;
    }

    private static org.apache.log4j.Logger _logger =
        org.apache.log4j.Logger.getLogger(CheckVerificationRequestCommand.class);

    @Override
    public void execute() {
        DrawApplication app = DrawPlugin.getGui();
        Drawing drawing = app.drawing();

        app.getUndoRedoManager().prepareUndoSnapshot(drawing);

        if (!(drawing instanceof CPNDrawing)) {
            _logger.error("[Lola] Drawing needs to be a CPNDrawing. Aborting.");
            return;
        }

        FigureEnumeration figures = drawing.figures();

        // create lola file
        Boolean changed = false;
        while (figures.hasMoreElements()) {
            Figure fig = figures.nextElement();
            if (fig instanceof TextFigure) {
                TextFigure textFig = (TextFigure) fig;
                String text = textFig.getText();
                if (text.toLowerCase().startsWith("formula")) {
                    LolaTask task = new LolaTask((TextFigure) fig, (CPNDrawing) drawing);
                    task.check(new LolaAnalyzer(_lolaPath));
                    task.colorFigure();
                    fig.changed();
                    changed = true;
                }
            } else { // if we are not a TextFigure
                _logger.info("[Lola] Currently only checking TextFigures.");
            }
        }
        if (changed) {
            DrawPlugin.getGui().view().checkDamage();
            app.getUndoRedoManager().commitUndoSnapshot(drawing);
        }
    }

    @Override
    public void execute(String[] args, PrintStream response) {
        // TODO Auto-generated method stub
    }

    @Override
    public String getDescription() {
        // TODO Auto-generated method stub
        return null;
    }
}
