package edu.sc.seis.gee.task;

import java.io.File;
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.fissuresUtil.xml.DataSet;
import edu.sc.seis.fissuresUtil.xml.DataSetToXML;
import edu.sc.seis.fissuresUtil.xml.SeismogramFileTypes;
import edu.sc.seis.gee.CommonAccess;
import edu.sc.seis.gee.FrameManager;
import edu.sc.seis.gee.configurator.ConfigurationException;
import edu.sc.seis.gee.task.dataSetBrowser.DataSetBrowser;

/**
 * SaveDataSetTask.java
 *
 *
 * Created: Fri Jan 18 15:41:26 2002
 *
 * @author <a href="mailto:">Srinivasa Telukutla</a>
 * @version
 */

public class SaveDataSetTask implements Task {
    /**
     * Creates a new <code>SaveDataSetTask</code> instance.
     *
     */
    public SaveDataSetTask (){

    }

    /**
     * Describe <code>invoke</code> method here.
     *
     */
    public void invoke() throws ConfigurationException {
        createGUI();
    }

    public void destroy(){}

    public void createGUI() throws ConfigurationException {
        CommonAccess commonAccess = CommonAccess.getCommonAccess();
        DataSet[] dsToSave = null;
        if (params.containsKey("datasetbrowser")) {
            String browserId = (String)params.get("datasetbrowser");
            TaskAction browserAction =
                CommonAccess.getCommonAccess().getTaskAction(browserId);
            DataSetBrowser browser = (DataSetBrowser)browserAction.getTask();
            dsToSave = browser.getSelectedDataSets();
        } else {
            dsToSave = new DataSet[1];
            dsToSave[0] = commonAccess.getDataSetRoot();
            if (dsToSave[0].getDataSetNames().length == 1 &&
                dsToSave[0].getParameterNames().length == 0 &&
                dsToSave[0].getDataSetSeismogramNames().length == 0) {
                // in case of only one dataset in top level, don't save
                // the top level as it is just an extra layer
                dsToSave[0] = dsToSave[0].getDataSet(dsToSave[0].getDataSetNames()[0]);
            }
        } // end of else

        final JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        String extensions[] = new String[1];
        extensions[0] = "dsml";
        fc.setFileFilter(new FileNameFilter(extensions));

        fc.setDialogTitle("Save Dataset");
        String defName = "Mydata";
        if (dsToSave.length == 1) {
            defName = dsToSave[0].getName();
            defName = defName.replaceAll(" ","_");
            defName = defName.replaceAll(",","_");
            fc.setDialogTitle(defName);
        }
        fc.setSelectedFile(new File(defName));

        int returnVal = fc.showSaveDialog(FrameManager.getManager().getCurrentFrame());


        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();

            DSSaver saver = new DSSaver(defName, dsToSave, file, SeismogramFileTypes.SAC);
            JobTracker.getTracker().add(saver);
            WorkerThreadPool.getDefaultPool().invokeLater(saver);
        } else {
            //log.append("Open command cancelled by user.");
        }
    }

    class DSSaver extends AbstractJob {
        DSSaver(String dsname, DataSet[] dsToSave, File file, SeismogramFileTypes fileType) {
            super("Save Dataset "+dsname);
            this.dsToSave = dsToSave;
            this.file = file;
            this.fileType = fileType;
        }
        public void runJob() {
            try {
                DataSetToXML dataSetToXML = new DataSetToXML();
                for (int i = 0; i < dsToSave.length; i++) {
                    setStatus("Saving "+dsToSave[i].getName());
                    File out = dataSetToXML.save(dsToSave[i], file, fileType);
                }
                setFinished();
            } catch(Exception e) {
                GlobalExceptionHandler.handle("Problem saving dataset.",e);
            }
        }
        File file;
        DataSet[] dsToSave;
        SeismogramFileTypes fileType;
    }

    /**
     * gets the configuration parameters specified in the configuration file.
     *
     * @param params a <code>java.util.Map</code> value
     */
    public void configure(java.util.Map params) {
        this.params = params;
    }

    java.util.Map params;

    String seisFileType = "SAC";

    static final String SAC = "SAC";
    static final String MSEED = "MSEED";

}// SaveDataSetTask
