package org.khelekore.jsizer;

import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.JFrame;

/** An action that exports an image of the current graph. */
abstract class ExportImageAction extends AbstractAction {
    private SizePanel sp;
    private JFrame f;
    private JFileChooser chooser = new JFileChooser ();

    public ExportImageAction (String title, SizePanel sp, JFrame f) {
	super (title);
	this.sp = sp;
	this.f = f;
    }

    public void actionPerformed (ActionEvent e) {
	// TODO: add size and transparency options...
	try {
	    chooser.setFileSelectionMode (JFileChooser.FILES_ONLY);
	    String ext = getFileExtension ();
	    int returnVal = chooser.showDialog (f, "Save " + ext + " image");
	    if (returnVal != JFileChooser.APPROVE_OPTION)
		return;
	    File selected = chooser.getSelectedFile ();
	    ext = "." + ext;
	    if (!selected.getName ().toLowerCase ().endsWith (ext)) {
		File p = selected.getParentFile ();
		selected = new File (p, selected.getName () + ext);
	    }
	    f.setCursor (Cursor.getPredefinedCursor (Cursor.WAIT_CURSOR));
	    try {
		sp.setDoubleBuffered (false);
		writeImage (sp, selected);
		sp.setDoubleBuffered (true);
	    } finally {
		f.setCursor (null);
	    }
	} catch (IOException ex) {
	    ex.printStackTrace ();
	}
    }

    /** get the filename extension for the exported image, typically "png" or "pdf".
     */
    protected abstract String getFileExtension ();
    
    protected abstract void writeImage (SizePanel sp, File out) throws IOException;
}
