/**
 * CopyFromJarTask.java
 *
 * @author Created by Omnicore CodeGuide
 */

package edu.sc.seis.gee.task;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import edu.sc.seis.fissuresUtil.exceptionHandler.GlobalExceptionHandler;
import edu.sc.seis.gee.FrameManager;
import edu.sc.seis.gee.configurator.ConfigurationException;



public class CopyFromJarTask extends PlaceholderImage {

    public void configure(Map params) throws ConfigurationException {
        super.configure(params);
        if (params.containsKey("saveButtonName")) {
            buttonName = (String)params.get("saveButtonName");
        }
        if(params.containsKey("outputDirectoryName")){
            outputDirName = (String)params.get("outputDirectoryName");
        }
    }

    public void invoke() {
        if (panel == null) {
            // only do the copy on invoke if this is not being used as a gui
            // task, otherwise wait for user to click button
            copy();
        }
    }

    /**
     * Method getGUI
     *
     * @return   a JComponent
     *
     * @exception   ConfigurationException
     *
     */
    public JComponent getGUI() throws ConfigurationException {
        JComponent superComponent =  super.getGUI();
        JPanel myPanel = new JPanel();
        myPanel.setLayout(new BorderLayout());
        myPanel.add(superComponent, BorderLayout.CENTER);
        JButton copy = new JButton(buttonName);
        copy.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        copy();
                    }
                });
        myPanel.add(copy, BorderLayout.SOUTH);
        return myPanel;
    }

    void copy() {
        Iterator it = params.keySet().iterator();
        String outDirname = chooseOutputFile();
        if (outDirname == null) {
            //user cancelled from file chooser
            return;
        }
        File outDir = new File(outDirname);
        outDir.mkdirs();

        while (it.hasNext()) {
            String key = (String)it.next();
            Object val = params.get(key);
            if (key.startsWith("copy")) {
                String filename = (String)val;
                File outFile = new File(outDir, filename.substring(filename.lastIndexOf("/")));
                try {
                    URL resourceURL = getClass().getClassLoader().getResource(filename);
                    BufferedInputStream in = new BufferedInputStream(resourceURL.openStream());
                    BufferedOutputStream out =
                        new BufferedOutputStream(new FileOutputStream(outFile));
                    byte[] tmp = new byte[512];
                    int numRead = in.read(tmp, 0, tmp.length);
                    while (numRead > 0) {
                        out.write(tmp, 0, numRead);
                        numRead = in.read(tmp, 0, tmp.length);
                    }
                    in.close();
                    in = null;
                    out.close();
                    out = null;
                } catch(FileNotFoundException e) {
                    // shouldn't happen as we just created the parent dir
                    GlobalExceptionHandler.handle("Problem saving "+filename+" to "+outFile.getAbsolutePath(), e);
                } catch(IOException e) {
                    GlobalExceptionHandler.handle("Problem saving "+filename+" to "+outFile.getAbsolutePath(), e);
                }
            }
        }
    }


    private String chooseOutputFile() {
        final JFileChooser fc = new JFileChooser();
        fc.setDialogTitle("Save to Directory");
        fc.setSelectedFile(new File(outputDirName));

        int returnVal = fc.showSaveDialog(null);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            if (file.exists() && file.isDirectory()==false) {
                Object[] options = new String[3];
                options[0] = "Replace";
                options[1] = "Choose Again";
                options[2] = "Cancel";
                int n = JOptionPane.showOptionDialog(FrameManager.getManager().getCurrentFrame(),
                                                     "File "+file.getName()+" exists, replace?",
                                                     "File Exists",
                                                     JOptionPane.YES_NO_CANCEL_OPTION,
                                                     JOptionPane.QUESTION_MESSAGE,
                                                     null,     //don't use a custom Icon
                                                     options,  //the titles of buttons
                                                     options[0]); //default button title);
                if (n == JOptionPane.CANCEL_OPTION) {
                    return null;
                } else if (n == JOptionPane.CANCEL_OPTION) {
                    return chooseOutputFile();
                }
                // ok to replace...
                file.delete();
            }
            String fileName = file.getAbsolutePath();

            return file.getAbsolutePath();
        } else {
            //log.append("Open command cancelled by user.");
        }
        return null;
    }


    String buttonName = "Save Locally";

    String outputDirName = "output";
}


