package de.renew.fa.commands;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import CH.ifa.draw.DrawPlugin;
import CH.ifa.draw.util.Command;
import de.renew.draw.storables.ontology.Drawing;
import de.renew.fa.service.JflapFileCreator;
import de.renew.ioontology.exporting.ExportFormat;

/**
 * Commands are typically reflected in a JMenuBar but this command is currently not reflected there.
 * The export via File -> Export -> Export current drawing is added in {@link de.renew.fa.FAPlugin#init}.
 * See {@link de.renew.draw.storables.api.StorableApi#addExportFormat(ExportFormat)}.
 *
 * @author Cabac
 */
public class ExportJflapCommand extends Command {
    private static final org.apache.log4j.Logger LOGGER =
        org.apache.log4j.Logger.getLogger(ExportJflapCommand.class);

    /**
     * Constructs a ExportJflapCommand to be used to trigger an export to JFlap format.
     *
     * @param name the name of the command
     */
    public ExportJflapCommand(String name) {
        super(name);
    }

    @Override
    public void execute() {
        Drawing drawing = DrawPlugin.getGui().drawing();
        String name = drawing.getName();
        File path = drawing.getFilename().getParentFile();
        File file = new File(path, name + ".jff");
        OutputStream stream;
        try {
            stream = new FileOutputStream(file);
            JflapFileCreator.export(stream, drawing);
            stream.close();
        } catch (IOException e) {
            LOGGER.error(ExportJflapCommand.class.getName() + ": ", e);
        }
    }
}