package usda.weru.mcrew;

import de.schlichtherle.truezip.file.TFile;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.concurrent.CountDownLatch;
import usda.weru.util.WepsFileChooser;

/**
 *
 * @author jonathanhornbaker
 */
public class ExtensionSelector extends javax.swing.JFrame {

    public static final long serialVersionUID = 789423789L;
    
    private String destDir;
    private String extension;
    private final CountDownLatch state = new CountDownLatch(1);
    private boolean accepted = false;
    
    /**
     * Creates new form ExtensionSelector
     */
    public ExtensionSelector(String startDir) 
    {
        initComponents();
        destDir = startDir;
        TF_destDir.setText(destDir);
        extension = TF_suffix.getText();
        this.getRootPane().setDefaultButton(JB_OK);
    }
    
    public String getDestination() 
    {
        TFile dest = new TFile(destDir);
        if(!dest.isDirectory()) return "";
        else return dest.getAbsolutePath();
    }
    
    public String getExtension()
    {
        if(extension.trim().endsWith(".man"))  return extension.trim();
        else return extension.trim() + ".man";
    }

    /**
     * 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("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        JL_destDir = new javax.swing.JLabel();
        TF_destDir = new javax.swing.JTextField();
        JB_destDir = new javax.swing.JButton();
        JL_suffix = new javax.swing.JLabel();
        TF_suffix = new javax.swing.JTextField();
        JL_asterisk = new javax.swing.JLabel();
        JB_OK = new javax.swing.JButton();
        JB_cancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(JL_destDir, org.openide.util.NbBundle.getMessage(ExtensionSelector.class, "ExtensionSelector.JL_destDir.text")); // NOI18N

        TF_destDir.setText(org.openide.util.NbBundle.getMessage(ExtensionSelector.class, "ExtensionSelector.TF_destDir.text")); // NOI18N
        TF_destDir.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                TF_destDirFocusLost(evt);
            }
        });
        TF_destDir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TF_destDirActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(JB_destDir, org.openide.util.NbBundle.getMessage(ExtensionSelector.class, "ExtensionSelector.JB_destDir.text")); // NOI18N
        JB_destDir.setMaximumSize(new java.awt.Dimension(90, 25));
        JB_destDir.setMinimumSize(new java.awt.Dimension(90, 25));
        JB_destDir.setPreferredSize(new java.awt.Dimension(90, 25));
        JB_destDir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JB_destDirActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(JL_suffix, org.openide.util.NbBundle.getMessage(ExtensionSelector.class, "ExtensionSelector.JL_suffix.text")); // NOI18N

        TF_suffix.setText(org.openide.util.NbBundle.getMessage(ExtensionSelector.class, "ExtensionSelector.TF_suffix.text")); // NOI18N
        TF_suffix.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                TF_suffixFocusLost(evt);
            }
        });
        TF_suffix.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                TF_suffixActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(JL_asterisk, org.openide.util.NbBundle.getMessage(ExtensionSelector.class, "ExtensionSelector.JL_asterisk.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(JB_OK, org.openide.util.NbBundle.getMessage(ExtensionSelector.class, "ExtensionSelector.JB_OK.text")); // NOI18N
        JB_OK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JB_OKActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(JB_cancel, org.openide.util.NbBundle.getMessage(ExtensionSelector.class, "ExtensionSelector.JB_cancel.text")); // NOI18N
        JB_cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JB_cancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(TF_destDir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(JB_destDir, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(JL_destDir)
                            .addComponent(JL_suffix))
                        .addGap(0, 480, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(JL_asterisk)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(TF_suffix))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(JB_OK)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(JB_cancel)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(JL_destDir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(TF_destDir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(JB_destDir, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(10, 10, 10)
                .addComponent(JL_suffix)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(TF_suffix, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(JL_asterisk))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(JB_cancel)
                    .addComponent(JB_OK))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void TF_suffixFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_TF_suffixFocusLost
        recieveExtensionText();
    }//GEN-LAST:event_TF_suffixFocusLost

    private void TF_destDirFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_TF_destDirFocusLost
        recieveDestinationText();
    }//GEN-LAST:event_TF_destDirFocusLost

    private void JB_destDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_destDirActionPerformed
        WepsFileChooser fileChooser = new WepsFileChooser(WepsFileChooser.Filetype.FILE, "", WepsFileChooser.SELECT);
        fileChooser.setFileSelectionMode(WepsFileChooser.DIRECTORIES_ONLY);
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.setDialogTitle("Select a destination directory.");
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.setApproveButtonText("Choose Directory");

        TFile ddir = new TFile(destDir);
        fileChooser.setCurrentDirectory(ddir);

        int returnVal = fileChooser.showOpenDialog(this);

        if (returnVal == WepsFileChooser.APPROVE_OPTION) 
        {
            try { destDir = new TFile(fileChooser.getSelectedFile().getCanonicalPath() + TFile.separator).getAbsolutePath(); } 
            catch (Exception e) { System.err.println("Error: " + e); }
        }
        TF_destDir.setText(destDir);
    }//GEN-LAST:event_JB_destDirActionPerformed

    private void JB_cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_cancelActionPerformed
        close();
    }//GEN-LAST:event_JB_cancelActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        try {
            JB_cancel.doClick();
        } catch (java.lang.Exception e) {
        }
    }//GEN-LAST:event_formWindowClosing

    private void JB_OKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_OKActionPerformed
        accepted = true;
        close();
    }//GEN-LAST:event_JB_OKActionPerformed

    private void TF_destDirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TF_destDirActionPerformed
        recieveDestinationText();
    }//GEN-LAST:event_TF_destDirActionPerformed

    private void TF_suffixActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_TF_suffixActionPerformed
        recieveExtensionText();
    }//GEN-LAST:event_TF_suffixActionPerformed

    private void recieveExtensionText()
    {
        extension = TF_suffix.getText();
    }
    
    private void recieveDestinationText()
    {
        destDir = TF_destDir.getText();
    }
    
    private void close()
    {
        state.countDown();
        this.dispose();
    }
    
    public boolean recieveInput()
    {
        
        this.setVisible(true);
        this.revalidate();
        this.repaint();
        try { state.await(); }
        catch(InterruptedException inex) {}
        return accepted;
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ExtensionSelector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ExtensionSelector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ExtensionSelector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ExtensionSelector.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ExtensionSelector("/home/jonathanhornbaker/").setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton JB_OK;
    private javax.swing.JButton JB_cancel;
    private javax.swing.JButton JB_destDir;
    private javax.swing.JLabel JL_asterisk;
    private javax.swing.JLabel JL_destDir;
    private javax.swing.JLabel JL_suffix;
    private javax.swing.JTextField TF_destDir;
    private javax.swing.JTextField TF_suffix;
    // End of variables declaration//GEN-END:variables
}
