/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cobi.kgg.ui.dialog;

import java.io.File;
import javax.swing.JFileChooser;
import org.cobi.kgg.business.entity.Project;
import org.cobi.kgg.ui.GlobalManager;
import org.cobi.kgg.ui.KGGJFileChooser;
import org.cobi.kgg.ui.action.DefineSeedGeneDialogAction;
import org.cobi.kgg.ui.action.LoadPValueAction;
import org.openide.DialogDisplayer;
import org.openide.ErrorManager;
import org.openide.NotifyDescriptor;
import org.openide.awt.StatusDisplayer;
import org.openide.util.ImageUtilities;
import org.openide.util.actions.CallableSystemAction;
import org.openide.windows.WindowManager;

/**
 *
 * @author mxli
 */
public class CreateProjectDialog extends javax.swing.JDialog {

    /**
     * Creates new form CreateProjectDialog
     */
    public CreateProjectDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        setIconImage(ImageUtilities.loadImage("org/cobi/kgg/ui/png/16x16/logo1.png"));
    }

    /**
     * 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() {

        projectNameTextField = new javax.swing.JTextField();
        browseFolder = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        projectTextField = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jScrollPane = new javax.swing.JScrollPane();
        descriptionTextArea = new javax.swing.JTextArea();
        cancel = new javax.swing.JButton();
        createButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(org.openide.util.NbBundle.getMessage(CreateProjectDialog.class, "CreateProjectDialog.title")); // NOI18N

        projectNameTextField.setText(org.openide.util.NbBundle.getMessage(CreateProjectDialog.class, "CreateProjectDialog.projectNameTextField.text")); // NOI18N

        browseFolder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/cobi/kgg/ui/png/16x16/Folder.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(browseFolder, org.openide.util.NbBundle.getMessage(CreateProjectDialog.class, "CreateProjectDialog.browseFolder.text")); // NOI18N
        browseFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browseFolderActionPerformed(evt);
            }
        });

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

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

        projectTextField.setText(org.openide.util.NbBundle.getMessage(CreateProjectDialog.class, "CreateProjectDialog.projectTextField.text")); // NOI18N

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

        descriptionTextArea.setColumns(20);
        descriptionTextArea.setLineWrap(true);
        descriptionTextArea.setRows(5);
        descriptionTextArea.setText(org.openide.util.NbBundle.getMessage(CreateProjectDialog.class, "CreateProjectDialog.descriptionTextArea.text")); // NOI18N
        jScrollPane.setViewportView(descriptionTextArea);

        cancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/cobi/kgg/ui/png/16x16/Cancel.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(cancel, org.openide.util.NbBundle.getMessage(CreateProjectDialog.class, "CreateProjectDialog.cancel.text")); // NOI18N
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        createButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/cobi/kgg/ui/png/16x16/OK.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(createButton, org.openide.util.NbBundle.getMessage(CreateProjectDialog.class, "CreateProjectDialog.createButton.text")); // NOI18N
        createButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createButtonActionPerformed(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)
                    .addComponent(jLabel9)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(createButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(cancel))
                    .addComponent(jScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
                    .addComponent(projectNameTextField)
                    .addComponent(projectTextField))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(browseFolder, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(projectNameTextField, 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.CENTER)
                    .addComponent(jLabel9)
                    .addComponent(projectTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(browseFolder))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel8)
                    .addComponent(jScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(createButton)
                    .addComponent(cancel))
                .addContainerGap())
        );

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

    private void browseFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_browseFolderActionPerformed
        // TODO add your handling code here:
        JFileChooser fDialog = new KGGJFileChooser();
        fDialog.setDialogTitle("Choose KGG Project Path");
        fDialog.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int result = fDialog.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            try {
                GlobalManager.lastAccessedPath = fDialog.getSelectedFile().getCanonicalPath();
                projectTextField.setText(GlobalManager.lastAccessedPath + File.separator);
            } catch (Exception ex) {
                ErrorManager.getDefault().notify(ex);
            }

            if (projectNameTextField.getText().length() > 0) {
                File newFile = new File(projectTextField.getText() + File.separator + projectNameTextField.getText() + ".xml");
                if (newFile.exists()) {
                    NotifyDescriptor nd = new NotifyDescriptor.Message("Available project \"" + projectNameTextField.getText() + "\" in this folder!", NotifyDescriptor.ERROR_MESSAGE);
                    DialogDisplayer.getDefault().notifyLater(nd);
                }
            }
        }
    }//GEN-LAST:event_browseFolderActionPerformed

    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
        // TODO add your handling code here:
        setVisible(false);
    }//GEN-LAST:event_cancelActionPerformed

    private void createButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createButtonActionPerformed
        // TODO add your handling code here:
        String name = projectNameTextField.getText().trim();
        String path = projectTextField.getText().trim();

        if (name.length() == 0) {
            NotifyDescriptor nd = new NotifyDescriptor.Message("No Project Name!!", NotifyDescriptor.ERROR_MESSAGE);
            DialogDisplayer.getDefault().notifyLater(nd);
            return;
        }
        if (path.length() == 0) {
            NotifyDescriptor nd = new NotifyDescriptor.Message("No Project Working Folder!!", NotifyDescriptor.ERROR_MESSAGE);
            DialogDisplayer.getDefault().notifyLater(nd);
            return;
        }
        File newFile = new File(path + name + ".xml");
        if (newFile.exists()) {
            NotifyDescriptor nd = new NotifyDescriptor.Message("Available project \"" + name + "\" in the working folder!", NotifyDescriptor.ERROR_MESSAGE);
            DialogDisplayer.getDefault().notifyLater(nd);
            return;
        }

        Project newProject = new Project(name, path);
        newProject.setDescription(descriptionTextArea.getText());
        try {
            String msg = newProject.toString() + " has been created!";
            GlobalManager.currentProject = newProject;
            ProjectTopComponent projTopComp = (ProjectTopComponent) WindowManager.getDefault().findTopComponent("ProjectTopComponent");

            projTopComp.showProject(newProject);
            StatusDisplayer.getDefault().setStatusText(msg);
            if (!GlobalManager.latestAccessedProjects.contains(newFile.getCanonicalPath())) {
                GlobalManager.latestAccessedProjects.add(newFile.getCanonicalPath());
            }

            //GlobalManager.mainView.insertBriefRunningInfor(msg, true);
            //GlobalManager.addInforLog(msg);
            //GlobalManager.setCurrentProject(newProject);
            /*
             * if (GlobalManager.mainView.addProject2Tree(newProject)) {
             * JOptionPane.showMessageDialog(GlobalManager.mainFrame, "Project
             * \"" + name + "\" Created", "Message",
             * JOptionPane.INFORMATION_MESSAGE);
             * GlobalManager.latestAccessedProjects.add(path + name); //
             * GlobalManager.mainView.switchLoadPValues(true); //
             * GlobalManager.mainView.switchWeight(true); } else {
             * JOptionPane.showMessageDialog(GlobalManager.mainFrame, "Available
             * Project Name", "Error", JOptionPane.ERROR_MESSAGE);
             * setVisible(true); }
             */
            projTopComp.openAtTabPosition(0);
            projTopComp.requestActive();
            setVisible(false);
            CallableSystemAction.get(LoadPValueAction.class).setEnabled(true);
            CallableSystemAction.get(DefineSeedGeneDialogAction.class).setEnabled(true);
        } catch (Exception ex) {
            ErrorManager.getDefault().notify(ex);
        }
    }//GEN-LAST:event_createButtonActionPerformed

    /**
     * @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(CreateProjectDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CreateProjectDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CreateProjectDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CreateProjectDialog.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() {
                CreateProjectDialog dialog = new CreateProjectDialog(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 browseFolder;
    private javax.swing.JButton cancel;
    private javax.swing.JButton createButton;
    private javax.swing.JTextArea descriptionTextArea;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane;
    private javax.swing.JTextField projectNameTextField;
    private javax.swing.JTextField projectTextField;
    // End of variables declaration//GEN-END:variables
}
