package org.khelekore.jsizer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import javax.swing.JFrame;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.w3c.dom.DOMImplementation;
import org.w3c.dom.Document;

/** An action that exports a pdf image of the current graph. */
class SVGAction extends ExportImageAction {
    private static final long serialVersionUID = 1;

    public SVGAction (SizePanel sp, JFrame f) {
	super ("Save svg...", sp, f);
    }

    @Override protected String getFileExtension () {
	return "svg";
    }

    @Override protected void writeImage (SizePanel sp, File out) 
	throws IOException {
	// code mostly from batik tutorial...
        DOMImplementation domImpl =
            GenericDOMImplementation.getDOMImplementation ();
        String svgNS = "http://www.w3.org/2000/svg";
        Document document = domImpl.createDocument (svgNS, "svg", null);
        SVGGraphics2D svgGenerator = new SVGGraphics2D (document);
	sp.paint (svgGenerator);
        boolean useCSS = true; 
	Writer w = null;	
	try {
	    FileOutputStream fos = new FileOutputStream (out);
	    w = new OutputStreamWriter (fos, "UTF-8");
	    svgGenerator.stream (w, useCSS);
	} finally {
	    if (w != null) {
		try {
		    w.close ();
		} catch (IOException e) {
		    e.printStackTrace ();
		}
	    }
	}
    }
}
