package edu.sc.seis.gee.task;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.swing.JFileChooser;
import edu.sc.seis.fissuresUtil.cache.AbstractJob;
import edu.sc.seis.fissuresUtil.cache.JobTracker;
import edu.sc.seis.fissuresUtil.cache.WorkerThreadPool;
import edu.sc.seis.fissuresUtil.chooser.FileNameFilter;
import edu.sc.seis.fissuresUtil.exceptionHandler.GlobalExceptionHandler;
import edu.sc.seis.gee.FrameManager;
import edu.sc.seis.gee.configurator.ConfigurationException;

/**
 * @author oliverpa Created on Aug 24, 2004
 */
public abstract class DisplayOutputTask implements Task {

    public abstract void configure(Map params) throws ConfigurationException;

    public void invoke() throws Exception {
        createFileGUI();
    }

    public void destroy() {}

    protected void createFileGUI() throws ConfigurationException {
        final JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        String extensions[] = {"png"};
        fc.setFileFilter(new FileNameFilter(extensions));
        fc.setDialogTitle(dialogueTitle);
        String defName = "output.png";
        fc.setSelectedFile(new File(defName));
        int returnVal = fc.showSaveDialog(FrameManager.getManager()
                .getCurrentFrame());
        if(returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            Saver saver = new Saver(file);
            JobTracker.getTracker().add(saver);
            WorkerThreadPool.getDefaultPool().invokeLater(saver);
        } else {
            //log.append("Open command cancelled by user.");
        }
    }

    protected abstract void save(File file) throws IOException;

    protected class Saver extends AbstractJob {

        Saver(File file) {
            super("Save display image");
            this.file = file;
        }

        public void runJob() {
            try {
                save(file);
            } catch(IOException e) {
                GlobalExceptionHandler.handle("problem saving display to image file",
                                              e);
            }
            setFinished();
        }

        File file;
    }

    protected String dialogueTitle;
}