package _VisualDVM.Passes.All;
import Common.Passes.Pass;
import Common.Passes.PassException;
import Common.Utils.Utils_;
import Common.Visual.UI_;
import _VisualDVM.Global;
import _VisualDVM.ProjectData.SapforData.Functions.UI.Graph.FunctionsGraphForm;
import _VisualDVM.Visual.UI;
import com.mxgraph.io.mxCodec;
import com.mxgraph.util.mxCellRenderer;
import com.mxgraph.util.mxXmlUtils;
import com.mxgraph.util.png.mxPngEncodeParam;
import com.mxgraph.util.png.mxPngImageEncoder;
import com.mxgraph.view.mxGraph;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URLEncoder;
import java.nio.file.Paths;
public class SaveGraph extends Pass<File> {
    FunctionsGraphForm graphForm = null;
    @Override
    protected boolean needsAnimation() {
        return true;
    }
    @Override
    public String getIconPath() {
        return "/icons/ScreenShot.png";
    }
    @Override
    protected boolean canStart(Object... args) {
        graphForm = UI.getMainWindow().getProjectWindow().getFunctionsWindow().getFunctionsGraphWindow();
        if (!graphForm.isShown())
            Log.Writeln_("Сначала отобразите граф");
        if (Global.mainModule.getProject().functionsGraph.isEmpty())
            Log.Writeln_("Граф процедур пуст");
        return Log.isEmpty();
    }
    @Override
    protected void body() throws Exception {
        target = Paths.get(Global.visualiser.getWorkspace().getAbsolutePath(), "Graph.png").toFile();
        if (target.exists() && !target.delete())
            throw new PassException("Не удается удалить предыдущий файл " + Utils_.Brackets(target.getAbsolutePath()));
        //-
        mxGraph graph = graphForm.control.getGraph();
        BufferedImage image = mxCellRenderer.createBufferedImage(graph,
                null, 1, Color.WHITE,
                graphForm.control.isAntiAlias(),
                null,
                graphForm.control.getCanvas());
        // Creates the URL-encoded XML data
        mxCodec codec = new mxCodec();
        String xml = URLEncoder.encode(mxXmlUtils.getXml(codec.encode(graph.getModel())), "UTF-8");
        mxPngEncodeParam param = mxPngEncodeParam.getDefaultEncodeParam(image);
        param.setCompressedText(new String[]{"graph", xml});
        // Saves as a PNG file
        FileOutputStream outputStream = new FileOutputStream(target);
        mxPngImageEncoder encoder = new mxPngImageEncoder(outputStream, param);
        encoder.encode(image);
        outputStream.close();
    }
    @Override
    protected void showDone() throws Exception {
        UI_.Info("Граф успешно сохранен в файл: " + Utils_.Brackets(target.getAbsolutePath()));
    }
}
