package _VisualDVM.Passes.All;
import Common.Passes.Pass;
import Common.Utils.Utils_;
import Common.Visual.UI;
import Common.Visual.Windows.Dialog.VDirectoryChooser;
import _VisualDVM.Global;
import _VisualDVM.Passes.PassCode;
import _VisualDVM.ProjectData.SapforData.Functions.UI.Graph.FunctionsGraphForm;
import _VisualDVM.Utils;
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;
public class SaveGraph extends Pass<File> {
    VDirectoryChooser directoryChooser = new VDirectoryChooser("Выбор папки для сохранения скриншота графа функций");
    FunctionsGraphForm graphForm = null;
    @Override
    protected boolean needsAnimation() {
        return true;
    }
    @Override
    public String getIconPath() {
        return "/icons/ScreenShot.png";
    }
    @Override
    protected boolean canStart(Object... args) {
        graphForm = Global.mainModule.getUI().getMainWindow().getProjectWindow().getFunctionsWindow().getFunctionsGraphWindow();
        if (!graphForm.isShown())
            Log.Writeln_("Сначала отобразите граф");
        if (Global.mainModule.getProject().functionsGraph.isEmpty())
            Log.Writeln_("Граф процедур пуст");
        Utils.ChooseDocumentsDirectory(directoryChooser);
        File dir = directoryChooser.ShowDialog();
        if (dir == null) {
            Log.Writeln_("Папка не выбрана.");
        } else {
            Global.mainModule.getPass(PassCode.UpdateProperty).Do("DocumentsDirectory", dir.getAbsolutePath());
            target = new File(dir, Utils_.getDateName("Graph") + ".png");
            return true;
        }
        return false;
    }
    @Override
    protected void body() throws Exception {
        mxGraph graph = graphForm.getControl().getGraph();
        BufferedImage image = mxCellRenderer.createBufferedImage(graph,
                null, 1, Color.WHITE,
                graphForm.getControl().isAntiAlias(),
                null,
                graphForm.getControl().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 {
        if (UI.Question("Изображение графа процедур успешно сохранено\n"
                + "в папке " + Utils_.Brackets(target.getParent()) + "\n"
                + "под именем " + Utils_.Brackets(target.getName()) + "\n"
                + "Открыть его"
        )) {
            try {
                Desktop.getDesktop().open(target);
            } catch (Exception ex) {
                Utils_.MainLog.PrintException(ex);
            }
        }
        ;
    }
}
