/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import database.DatabaseInterface;
import java.awt.Rectangle;
import java.util.HashMap;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author smuRf
 */
public class DetectionDialogLarge extends javax.swing.JDialog {
    private int selectedListIndex = -1;
    private AnalyserForm parent;
    private DatabaseInterface databaseInterface;
    private HashMap<String, Integer> categories;
    private String username;
    
    /**
     * Creates new form DetectionDialog
     */
    public DetectionDialogLarge(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        
        this.parent = (AnalyserForm)parent;
        this.getRootPane().setDefaultButton(btnDetect);
        
        cbEquiMotifs.setSelected(true);
        
        Rectangle parentBounds = this.parent.getBounds();
        this.setBounds((int)(parentBounds.getWidth()/2-getBounds().getWidth()/2) + (int)parentBounds.getX(), 
                       (int)(parentBounds.getHeight()/2-getBounds().getHeight()/2) + (int)parentBounds.getY(), 
                       (int)getBounds().getWidth(), (int)getBounds().getHeight());
    }

    public void initCategories(String username) {
        this.username = username;
        
        databaseInterface = new DatabaseInterface(AnalyserForm.DB_USER, AnalyserForm.DB_PASSWORD, AnalyserForm.DB_URL);
        
        categories = databaseInterface.getCategoriesOrdered();
        
        DefaultListModel listModel = (DefaultListModel)listCategories.getModel();
        
        for(String name:categories.keySet())
            listModel.addElement(name);
        
        listCategories.setSelectedIndex(0);
    }
    
    /**
     * 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() {

        jLabel1 = new javax.swing.JLabel();
        pnlButtons = new javax.swing.JPanel();
        btnDetect = new javax.swing.JButton();
        btnCancel = new javax.swing.JButton();
        pnlCategory = new javax.swing.JPanel();
        spCategories = new javax.swing.JScrollPane();
        listCategories = new javax.swing.JList();
        cbNewCategory = new javax.swing.JCheckBox();
        tfNewCategory = new javax.swing.JTextField();
        cbEquiMotifs = new javax.swing.JCheckBox();

        jLabel1.setText("jLabel1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Add Motifs To Category");
        setMinimumSize(new java.awt.Dimension(449, 420));
        setResizable(false);

        pnlButtons.setPreferredSize(new java.awt.Dimension(400, 40));
        pnlButtons.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 2, 5));

        btnDetect.setText("detect");
        btnDetect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDetectActionPerformed(evt);
            }
        });
        pnlButtons.add(btnDetect);

        btnCancel.setText("cancel");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });
        pnlButtons.add(btnCancel);

        pnlCategory.setBorder(javax.swing.BorderFactory.createTitledBorder("Categories"));

        listCategories.setModel(new DefaultListModel());
        spCategories.setViewportView(listCategories);

        cbNewCategory.setText("new category:");
        cbNewCategory.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbNewCategoryActionPerformed(evt);
            }
        });

        tfNewCategory.setEditable(false);

        cbEquiMotifs.setText("add sub-motifs");

        javax.swing.GroupLayout pnlCategoryLayout = new javax.swing.GroupLayout(pnlCategory);
        pnlCategory.setLayout(pnlCategoryLayout);
        pnlCategoryLayout.setHorizontalGroup(
            pnlCategoryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 448, Short.MAX_VALUE)
            .addGroup(pnlCategoryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(pnlCategoryLayout.createSequentialGroup()
                    .addGap(31, 31, 31)
                    .addGroup(pnlCategoryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(pnlCategoryLayout.createSequentialGroup()
                            .addComponent(spCategories, javax.swing.GroupLayout.PREFERRED_SIZE, 385, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addContainerGap(32, Short.MAX_VALUE))
                        .addGroup(pnlCategoryLayout.createSequentialGroup()
                            .addGroup(pnlCategoryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(cbEquiMotifs, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(cbNewCategory, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(tfNewCategory)
                            .addGap(32, 32, 32)))))
        );
        pnlCategoryLayout.setVerticalGroup(
            pnlCategoryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 310, Short.MAX_VALUE)
            .addGroup(pnlCategoryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(pnlCategoryLayout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(spCategories, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(pnlCategoryLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cbNewCategory)
                        .addComponent(tfNewCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(cbEquiMotifs)
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(pnlCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(pnlButtons, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(20, 20, 20))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(pnlCategory, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(pnlButtons, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

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

    private void btnDetectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDetectActionPerformed
        String categoryName;
        
        if(cbNewCategory.isSelected())
        {
            categoryName = tfNewCategory.getText();
            if(categoryName.isEmpty())
            {
                JOptionPane.showMessageDialog(this, "You have to enter a category name", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
            
            databaseInterface.insertCategory(categoryName, username);
        }
        else
        {
            categoryName = (String) listCategories.getSelectedValue();
            if(categoryName == null)
            {
                JOptionPane.showMessageDialog(this, "You have to select a category", "Error", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
        
        int categoryId = databaseInterface.getCategoryIdForName(categoryName);
        
        parent.setStartDetect(true);
        parent.setCategoryID(categoryId);
        parent.setSubmotifs(cbEquiMotifs.isSelected());
        databaseInterface.closeConnection();
        JOptionPane.showMessageDialog(this, "This progress may take from several minutes up to hours,\ndepending on the amount of files.", "Information", JOptionPane.INFORMATION_MESSAGE);
        dispose();
    }//GEN-LAST:event_btnDetectActionPerformed

    private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
        dispose();
    }//GEN-LAST:event_btnCancelActionPerformed

    private void cbNewCategoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbNewCategoryActionPerformed
        if(cbNewCategory.isSelected())
        {
            listCategories.setEnabled(false);
            tfNewCategory.setEditable(true);
            selectedListIndex = listCategories.getSelectedIndex();
            listCategories.clearSelection();
        }
        else
        {
            listCategories.setEnabled(true);
            tfNewCategory.setEditable(false);
            listCategories.setSelectedIndex(selectedListIndex);
            tfNewCategory.setText("");
        }
    }//GEN-LAST:event_cbNewCategoryActionPerformed

    /**
     * @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(DetectionDialogLarge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DetectionDialogLarge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DetectionDialogLarge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DetectionDialogLarge.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                DetectionDialogLarge dialog = new DetectionDialogLarge(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancel;
    private javax.swing.JButton btnDetect;
    private javax.swing.JCheckBox cbEquiMotifs;
    private javax.swing.JCheckBox cbNewCategory;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JList listCategories;
    private javax.swing.JPanel pnlButtons;
    private javax.swing.JPanel pnlCategory;
    private javax.swing.JScrollPane spCategories;
    private javax.swing.JTextField tfNewCategory;
    // End of variables declaration//GEN-END:variables
}
