/*
 * RunExporter.java
 *
 * Created on February 4, 2008, 2:52 PM
 */
package usda.weru.weps;

import de.schlichtherle.truezip.file.TFile;
import java.awt.Component;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import org.apache.log4j.Logger;
import org.jdesktop.beansbinding.Converter;
import usda.weru.util.Util;
import usda.weru.util.WepsFileField;

/**
 *
 * @author  Joseph Levin <joelevin@weru.ksu.edu>
 */
public class RunExporter extends javax.swing.JPanel {

    private static final long serialVersionUID = 1L;

    private static final Logger logger = Logger.getLogger(RunExporter.class);

    /**
     *
     */
    public static final String PROP_SOURCERUN = "sourceRunFile";

    /**
     *
     */
    public static final String PROP_DESTRUN = "destinationRunFile";

    /**
     *
     */
    public static final String PROP_REMOVESOURCE = "removeSource";
    private TFile c_sourceRun;
    private TFile c_dest;
    private boolean c_removeSource;

    /** Creates new form RunExporter */
    public RunExporter() {
        initComponents();
        g_source.setMode(WepsFileField.MODE.SELECT);
        g_source.setFileType(WepsFileField.TYPE.RUN);

        g_dest.setMode(WepsFileField.MODE.SELECT);
        g_dest.setFileType(WepsFileField.TYPE.DIRECTORY);
    }

    /**
     *
     * @param source
     * @param dest
     * @param removeSource
     */
    public RunExporter(TFile source, TFile dest, boolean removeSource) {
        this();
        setSourceRunFile(source);
        setDestinationFile(dest);
        setRemoveSource(removeSource);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("rawtypes")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        g_sourceLabel = new javax.swing.JLabel();
        g_destLabel = new javax.swing.JLabel();
        g_removeCheckBox = new javax.swing.JCheckBox();
        g_source = new usda.weru.util.WepsFileField();
        g_source.setFileType(WepsFileField.TYPE.RUN);
        g_dest = new usda.weru.util.WepsFileField();
        g_dest.setFileType(WepsFileField.TYPE.DIRECTORY);

        setMinimumSize(new java.awt.Dimension(350, 75));

        g_sourceLabel.setText("Run:");

        g_destLabel.setText("Export into:");

        g_removeCheckBox.setText("Remove source run after successful export.");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${removeSource}"), g_removeCheckBox, org.jdesktop.beansbinding.BeanProperty.create("selected"));
        bindingGroup.addBinding(binding);

        g_removeCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                g_removeCheckBoxActionPerformed(evt);
            }
        });

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${sourceRunFile}"), g_source, org.jdesktop.beansbinding.BeanProperty.create("file"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${destinationFile}"), g_dest, org.jdesktop.beansbinding.BeanProperty.create("file"));
        bindingGroup.addBinding(binding);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(g_destLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(g_sourceLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(g_dest, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE)
                    .addComponent(g_source, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE))
                .addGap(0, 0, 0))
            .addGroup(layout.createSequentialGroup()
                .addComponent(g_removeCheckBox, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(g_sourceLabel)
                    .addComponent(g_source, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(g_destLabel)
                    .addComponent(g_dest, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(g_removeCheckBox)
                .addContainerGap())
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents

    private void g_removeCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_g_removeCheckBoxActionPerformed
}//GEN-LAST:event_g_removeCheckBoxActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private usda.weru.util.WepsFileField g_dest;
    private javax.swing.JLabel g_destLabel;
    private javax.swing.JCheckBox g_removeCheckBox;
    private usda.weru.util.WepsFileField g_source;
    private javax.swing.JLabel g_sourceLabel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    /**
     *
     * @param parent
     */
    public void display(Component parent) {
        JOptionPane pane = new JOptionPane(this, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION,
                null, new String[]{"Export", "Cancel"}, "Export");
        JDialog dialog = pane.createDialog(parent, "Run Exporter");
        dialog.setResizable(true);
        dialog.setVisible(true);
        if ("Export".equals(pane.getValue())) {

            if (c_sourceRun == null || !c_sourceRun.exists()) {
                JOptionPane.showMessageDialog(this, "The specified source run does not exist.",
                        "Error", JOptionPane.ERROR_MESSAGE);
                display(parent);
                g_source.requestFocus();
                return;
            }

            if (c_dest == null || !c_dest.isDirectory()) {
                JOptionPane.showMessageDialog(this, "The specified export location does not exist.",
                        "Error", JOptionPane.ERROR_MESSAGE);
                display(parent);
                g_source.requestFocus();
                return;
            }

            TFile destRun = new TFile(c_dest, c_sourceRun.getName());

            if (destRun.exists()) {
                //Confirm the overwrite.
                String cutPath = destRun.getAbsolutePath();
                int sub = cutPath.length() - 40;
                if (sub > 0) {
                    cutPath = cutPath.substring(sub);
                    cutPath = "..." + cutPath;
                }

                int overwrite = JOptionPane.showOptionDialog(this, "The file: \"" + cutPath
                        + "\" already exits.\nDo you want to overwrite the file?", "Confirm Overwrite",
                        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE,
                        null, new String[]{"Overwrite", "No"}, "No");
                if (overwrite != JOptionPane.YES_OPTION) {
                    display(parent);
                    return;
                }
            }

            boolean copied = Util.copyDirectory(c_sourceRun, destRun, true);
            if (!copied) {
                //Tell the user we couldn't copy everything
                JOptionPane.showMessageDialog(this, "Unable to successfully export run.",
                        "Error", JOptionPane.ERROR_MESSAGE);
                display(parent);
                g_source.requestFocus();
                return;
            }

            if (copied && c_removeSource) {
                boolean removed = Util.deleteAll(c_sourceRun);
                if (!removed) {
                    //tell user we couldn't remove the source run.
                    JOptionPane.showMessageDialog(this, "Unable to successfully remove source run.",
                            "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    /**
     *
     * @return
     */
    public TFile getSourceRunFile() {
        return c_sourceRun;
    }

    /**
     *
     * @param run
     */
    public void setSourceRunFile(TFile run) {
        TFile old = c_sourceRun;
        c_sourceRun = run;
        firePropertyChange(PROP_SOURCERUN, old, c_sourceRun);
    }

    /**
     *
     * @return
     */
    public TFile getDestinationFile() {
        return c_sourceRun;
    }

    /**
     *
     * @param run
     */
    public void setDestinationFile(TFile run) {
        TFile old = c_dest;
        c_dest = run;
        firePropertyChange(PROP_DESTRUN, old, c_dest);
    }

    /**
     *
     * @return
     */
    public boolean isRemoveSource() {
        return c_removeSource;
    }

    /**
     *
     * @param remove
     */
    public void setRemoveSource(boolean remove) {
        boolean old = c_removeSource;
        c_removeSource = remove;
        firePropertyChange(PROP_REMOVESOURCE, old, c_removeSource);
    }

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        RunExporter exporter = new RunExporter();
        exporter.display(null);

    }

    /**
     *
     */
    public static class BindingFileToString extends Converter<TFile, String> {

        /**
         *
         * @param file
         * @return
         */
        @Override
        public String convertForward(TFile file) {
            if (file != null) {
                return file.getPath();
            } else {
                return null;
            }
        }

        /**
         *
         * @param path
         * @return
         */
        @Override
        public TFile convertReverse(String path) {
            if (path != null) {
                return new TFile(path);
            } else {
                return null;
            }
        }
    }
}
