package de.renew.io.exportFormats;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import de.renew.draw.storables.ontology.Drawing;
import de.renew.draw.storables.ontology.exporting.AbstractDrawingExportFormat;
import de.renew.gui.CPNDrawing;
import de.renew.gui.ModeReplacement;
import de.renew.io.FileFilterCreator;
import de.renew.shadowcompiler.ShadowNetSystemCreator;
import de.renew.simulatorontology.shadow.ShadowNetSystem;

/**
 * Formats SNS Files for Export.
 */
public class SNSExportFormat extends AbstractDrawingExportFormat {
    // Attributes
    // Construktor

    /**
     * Creates a Formatter for SNS Files for Export.
     */
    public SNSExportFormat() {
        super("ShadowNetSystem", FileFilterCreator.createSNSFileFilter());
    }

    // Methods


    @Override
    public boolean canExportNto1() {
        return true;
    }

    @Override
    public File export(Drawing drawing, File path) throws Exception {
        File result = null;
        if (drawing != null && path != null) {
            result = path;
            FileOutputStream stream = new FileOutputStream(result);
            ObjectOutput output = new ObjectOutputStream(stream);
            ShadowNetSystem netSystem = ShadowNetSystemCreator
                .createWithCompiler(ModeReplacement.getInstance().getDefaultCompilerFactory());
            CPNDrawing cpndrawing = (CPNDrawing) drawing;
            cpndrawing.buildShadow(netSystem);
            output.writeObject(netSystem);
            output.close();
        }
        assert (result != null) : "Failure in SNSExportFormat: result == null";
        return result;
    }

    @Override
    public File export(Drawing[] drawings, File path) throws Exception {
        File result = null;
        if (drawings != null && path != null) {
            result = path;
            FileOutputStream stream = new FileOutputStream(result);
            ObjectOutput output = new ObjectOutputStream(stream);
            ShadowNetSystem system = ShadowNetSystemCreator
                .createWithCompiler(ModeReplacement.getInstance().getDefaultCompilerFactory());
            for (Drawing value : drawings) {
                CPNDrawing drawing = (CPNDrawing) value;
                drawing.buildShadow(system);
            }
            output.writeObject(system);
            output.close();
        }
        assert (result != null) : "Failure in SNSExportFormat: result == null";
        return result;
    }

    @Override
    public boolean canExportDrawing(Drawing drawing) {
        return drawing instanceof CPNDrawing;
    }
}