/* Copyright Nabil Alikhan. 2010.
 * This file is part of BLAST Ring Image Generator (BRIG).
 * BRIG is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * BRIG is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 *  along with BRIG.  If not, see <http://www.gnu.org/licenses/>.
 */


package brig;

import java.awt.Color;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
 *
 * @author Nabil
 */

public class One extends javax.swing.JFrame {
private DefaultListModel refModel;
    /** Creates new form One */
    public One() {
        refModel = new DefaultListModel();
        initComponents();
        refAddButton.setToolTipText("This button will add query sequences from the specified directory that you can add to image rings");
        queryField.setToolTipText("This sequence will be the image backbone");
        jButton1.setToolTipText("Select a sequence and click here to remove it from the query sequence list");
        setTitle(BRIG.header + " - Select input data");
        reload();
    }
    /** 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() {

        jButton2 = new javax.swing.JButton();
        sequenceAddField = new javax.swing.JTextField();
        refBrowseButton = new javax.swing.JButton();
        refAddButton = new javax.swing.JButton();
        outputFolderField = new javax.swing.JTextField();
        blastOptionField = new javax.swing.JTextField();
        outputBrowseButton = new javax.swing.JButton();
        nextButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        queryField = new javax.swing.JTextField();
        queryBrowseButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList(refModel);
        jButton1 = new javax.swing.JButton();
        ringCheck = new javax.swing.JCheckBox();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        OpenMenu = new javax.swing.JMenuItem();
        SaveMenu = new javax.swing.JMenuItem();
        profileSave = new javax.swing.JMenuItem();
        Bundle = new javax.swing.JMenuItem();
        QuitMenu = new javax.swing.JMenuItem();
        jMenu3 = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem4 = new javax.swing.JMenuItem();
        jMenuItem6 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem5 = new javax.swing.JMenuItem();

        jButton2.setText("Change BLAST options");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        refBrowseButton.setText("Browse");
        refBrowseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refBrowseButtonActionPerformed(evt);
            }
        });

        refAddButton.setText("Add to data pool");
        refAddButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refAddButtonActionPerformed(evt);
            }
        });

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

        outputBrowseButton.setText("Browse");
        outputBrowseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                outputBrowseButtonActionPerformed(evt);
            }
        });

        nextButton.setText("Next >");
        nextButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextButtonActionPerformed(evt);
            }
        });

        jLabel1.setText("Reference / Database sequence:");

        jLabel2.setText("Query sequences folder:");

        jLabel3.setText("Output folder");

        jLabel4.setText("BLAST options");

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

        queryBrowseButton.setText("Browse");
        queryBrowseButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                queryBrowseButtonActionPerformed(evt);
            }
        });

        jScrollPane1.setViewportView(jList1);

        jButton1.setText("Remove");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        ringCheck.setText("Add as new ring");

        jMenu1.setText("File");

        jMenuItem1.setText("New");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        OpenMenu.setText("Open...");
        OpenMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                OpenMenuActionPerformed(evt);
            }
        });
        jMenu1.add(OpenMenu);

        SaveMenu.setText("Save As...");
        SaveMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveMenuActionPerformed(evt);
            }
        });
        jMenu1.add(SaveMenu);

        profileSave.setText("Save Profile..");
        profileSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                profileSaveActionPerformed(evt);
            }
        });
        jMenu1.add(profileSave);

        Bundle.setText("Bundle session...");
        Bundle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BundleActionPerformed(evt);
            }
        });
        jMenu1.add(Bundle);

        QuitMenu.setText("Quit");
        QuitMenu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                QuitMenuActionPerformed(evt);
            }
        });
        jMenu1.add(QuitMenu);

        jMenuBar1.add(jMenu1);

        jMenu3.setText("Modules");

        jMenuItem3.setText("Create graph files");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        jMenu3.add(jMenuItem3);

        jMenuBar1.add(jMenu3);

        jMenu2.setText("Preferences");

        jMenuItem4.setText("BRIG options");
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem4);

        jMenuItem6.setText("Load template");
        jMenuItem6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem6ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem6);

        jMenuItem2.setText("Image options");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem2);

        jMenuItem5.setText("About...");
        jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem5ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem5);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        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(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 730, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(sequenceAddField, javax.swing.GroupLayout.DEFAULT_SIZE, 529, Short.MAX_VALUE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(queryField, javax.swing.GroupLayout.DEFAULT_SIZE, 529, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(queryBrowseButton)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jButton1))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addComponent(refBrowseButton)
                                    .addGap(18, 18, 18)
                                    .addComponent(refAddButton)))
                            .addComponent(ringCheck))
                        .addGap(17, 17, 17))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(blastOptionField, javax.swing.GroupLayout.DEFAULT_SIZE, 553, Short.MAX_VALUE)
                            .addComponent(outputFolderField, javax.swing.GroupLayout.DEFAULT_SIZE, 553, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(outputBrowseButton)
                                .addGap(23, 23, 23))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(nextButton)
                                .addContainerGap())))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(queryField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(queryBrowseButton)
                    .addComponent(jButton1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(ringCheck))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(refBrowseButton)
                        .addComponent(refAddButton))
                    .addComponent(sequenceAddField, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 239, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(outputFolderField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(outputBrowseButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(blastOptionField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(43, 43, 43))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(nextButton, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );

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

    private void refBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refBrowseButtonActionPerformed
        File text = new File(sequenceAddField.getText());
        JFileChooser fc = new JFileChooser();
        if (text.isDirectory()) {
            fc = new JFileChooser(text.getParentFile().getAbsolutePath());
        }
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fc.showOpenDialog(this);
        if (fc.getSelectedFile() != null) {
            sequenceAddField.setText(fc.getSelectedFile().toString());
        }
    }//GEN-LAST:event_refBrowseButtonActionPerformed

    private void outputBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_outputBrowseButtonActionPerformed
        File text = new File(outputFolderField.getText());
        JFileChooser fc = new JFileChooser();
        if (text.isDirectory()) {
            fc = new JFileChooser(text.getParentFile().getAbsolutePath());
        }
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fc.showOpenDialog(this);
        if (fc.getSelectedFile() != null) {
            outputFolderField.setText(fc.getSelectedFile().toString());
        }
    }//GEN-LAST:event_outputBrowseButtonActionPerformed

    private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextButtonActionPerformed
        save();
        try{
        if(BRIG.isBlastOk()){
        String blastOpt = BRIG.BlastOption( blastOptionField.getText() );
        if (blastOpt  == null ) {
                String query = BRIG.PROFILE.getRootElement().getAttributeValue("queryFile");
                if (query.compareTo("") != 0) {
                    try {
                        String valid  = BRIG.ValidateSession();
                        if(valid == null ){
          /*                  if (Main.isEmbl(query) || Main.isGenbank(query)) {
                                Genbank check = new Genbank(this, true);
                                check.setVisible(true);
                                int protein = check.protein;
                                check.dispose();
                                if (protein == 0) {
                                    Main.PROFILE.getRootElement().removeAttribute("spacer");
                                    Main.PROFILE.getRootElement().removeAttribute("genbankProtein");
                                    new Two().setVisible(true);
                                } else if (protein == 1) {
                                    Main.PROFILE.getRootElement().setAttribute("spacer", "0");
                                    Main.PROFILE.getRootElement().setAttribute("genbankProtein", "true");
                                    new Two().setVisible(true);
                                }
                            } else {*/
                                new Two(this).setVisible(true);
                            //}
                        } else {
                            JOptionPane.showMessageDialog(this,
                                    valid,
                                    "ERROR!",
                                    JOptionPane.ERROR_MESSAGE);
                        }
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(this,
                                "Could not read reference file",
                                "ERROR!",
                                JOptionPane.ERROR_MESSAGE);
                        e.printStackTrace();
                    }
                } else {
                    JOptionPane.showMessageDialog(this,
                            "You are have not included a reference sequence",
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                }
            } else {
            JOptionPane.showMessageDialog(this,
                     blastOpt ,
                    "ERROR!",
                    JOptionPane.ERROR_MESSAGE);
            }
        }else{
                JOptionPane.showMessageDialog(this,
                        "Could not run BLAST, please check it is installed and BRIG's BLAST location is correct",
                        "ERROR!",
                        JOptionPane.ERROR_MESSAGE);
        }
        }catch(IOException e){
            JOptionPane.showMessageDialog(this,
                        "Could not run BLAST, please check it is installed and BRIG's BLAST location is correct",
                        "ERROR!",
                        JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_nextButtonActionPerformed

    private void refAddButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refAddButtonActionPerformed
        File add = new File(sequenceAddField.getText());
        if (add.exists()) {
            // get dir
            File dir = new File("");
            if (add.isFile()) {
                dir = new File(add.getParent());
            } else if (add.isDirectory()) {
                dir = add;
            }
            // check if dir exists in list
            List<Element> existDir = BRIG.PROFILE.getRootElement().getChildren("refDir");
            Element child = new Element("refDir");
            boolean exist = false;
            for (int i = 0; i < existDir.size(); i++) {
                if (dir.getAbsolutePath().compareTo(new File(existDir.get(i).getAttributeValue("location")).getAbsolutePath()) == 0) {
                    exist = true;
                    child = existDir.get(i);
                }
            }
            //if so & add = file, check if file exists, add to dir,
            Vector fil = SearchDir(dir.getAbsolutePath());
            List<Element> exFiles = child.getChildren("refFile");
            if (add.isFile()) {
                if (exist) {
                    for (int i = 0; i < fil.size(); i++) {
                        boolean fileExist = false;
                        for (int j = 0; j < exFiles.size(); j++) {
                            if (exFiles.get(j).getAttributeValue("location").compareTo(add.getAbsolutePath()) == 0) {
                                fileExist = true;
                            }
                        }
                        if (!exist || !fileExist) {
                            Element fileloc = new Element("refFile");
                            fileloc.setAttribute("location", add.getAbsolutePath());
                            child.addContent(fileloc);
                        }
                    }
                } else {
                    Element fileloc = new Element("refFile");
                    fileloc.setAttribute("location", add.getAbsolutePath());
                    child.addContent(fileloc);
                    child.setAttribute("location", dir.getAbsolutePath());
                    if(ringCheck.isSelected()){
                        if(add.toString().length() > 1 ){
                        ringspoop(add.getAbsolutePath());
                        }
                    }
                    BRIG.PROFILE.getRootElement().addContent(child);
                }
            } else if (add.isDirectory()) {
                //if so & add = dir, check all files exist. add to dir,
                if (exist) {
                    for (int i = 0; i < fil.size(); i++) {
                        boolean fileExist = false;
                        for (int j = 0; j < exFiles.size(); j++) {
                            if (exFiles.get(j).getAttributeValue("location").compareTo(fil.get(i).toString()) == 0) {
                                fileExist = true;
                            }
                        }
                        if (!exist || !fileExist) {
                            Element fileloc = new Element("refFile");
                            fileloc.setAttribute("location", fil.get(i).toString());
                            if (ringCheck.isSelected()) {
                                if (fil.get(i).toString().length() > 1) {
                                    ringspoop(fil.get(i).toString());
                                }
                            }
                            child.addContent(fileloc);
                        }
                    }
                } else {
                    child.setAttribute("location", dir.getAbsolutePath());
                    for (int i = 0; i < fil.size(); i++) {
                        Element fileloc = new Element("refFile");
                        fileloc.setAttribute("location", fil.get(i).toString());
                        child.addContent(fileloc);
                        if (ringCheck.isSelected()) {
                            if(fil.get(i).toString().length() > 1 ){
                            ringspoop(fil.get(i).toString());
                            }
                        }
                    }
                    BRIG.PROFILE.getRootElement().addContent(child);
                }
            }
            //if not & add = dir, add dir and files.
            save();
            reload();
        } else {
            JOptionPane.showMessageDialog(this,
                    "File/directory does not exist",
                    "ERROR!",
                    JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_refAddButtonActionPerformed

    private void queryBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_queryBrowseButtonActionPerformed
        File text = new File (queryField.getText());
        JFileChooser fc = new JFileChooser();
        if(text.exists() ){
        if (text.getParentFile().isDirectory()) {
            fc = new JFileChooser(text.getParent());
        }
        }
        fc.showOpenDialog(this);

        if (fc.getSelectedFile() != null) {
            BRIG.PROFILE.getRootElement().setAttribute("queryFile", fc.getSelectedFile().toString());

        }
        reload();
    }//GEN-LAST:event_queryBrowseButtonActionPerformed

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

    private void SaveMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveMenuActionPerformed
        BRIG.PROFILE.getRootElement().setAttribute("queryFile", queryField.getText());
        BRIG.PROFILE.getRootElement().setAttribute("blastOptions", blastOptionField.getText());
        BRIG.PROFILE.getRootElement().setAttribute("outputFolder", outputFolderField.getText());
        BRIG.PROFILE.getRootElement().removeAttribute("archive");
        final JFileChooser fc = new JFileChooser();
        fc.showSaveDialog(this);
        if (fc.getSelectedFile() != null) {
            try {
                int j = BRIG.saveXML(fc.getSelectedFile().toString(),BRIG.PROFILE);
                if (j == 0) {
                    JOptionPane.showMessageDialog(this,
                            "Saved!",
                            "Saved!",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_SaveMenuActionPerformed

    private void OpenMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_OpenMenuActionPerformed
        final JFileChooser fc = new JFileChooser();
        fc.showOpenDialog(this);
        if (fc.getSelectedFile() != null) {
            try {
                SAXBuilder builder = new SAXBuilder();
                try {
                    Document temp = builder.build(fc.getSelectedFile().toString());
                    String bl = null;
                    if (temp.getRootElement().getAttributeValue("archive") != null) {
                        if (BRIG.PROFILE.getRootElement().getChild("brig_settings") != null) {
                            if (BRIG.PROFILE.getRootElement().getChild("brig_settings").getAttributeValue("blastLocation") != null) {
                                bl = BRIG.PROFILE.getRootElement().getChild("brig_settings").getAttributeValue("blastLocation");
                            }
                        }
                        temp = BRIG.FormatArchive(temp, fc.getSelectedFile().toString());
                    }
                    BRIG.PROFILE = temp;
                    BRIG.PROFILE_LOCATION = fc.getSelectedFile().toString();
                    if (temp.getRootElement().getAttributeValue("archive") != null) {
                        if (bl != null) {
                            if (BRIG.PROFILE.getRootElement().getChild("brig_settings") != null) {
                                BRIG.PROFILE.getRootElement().getChild("brig_settings").setAttribute("blastLocation", bl);
                            }
                        }
                    }
                    reload();
                } catch (JDOMException e) {
                    JOptionPane.showMessageDialog(this,
                            fc.getSelectedFile().toString() + " is corrupt because :\n" + e.getMessage(),
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                } catch (IOException e) {
                    JOptionPane.showMessageDialog(this,
                            "Could not read " + fc.getSelectedFile().toString() + " because :\n" + e.getMessage(),
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this,
                        "This is not a valid save file " + e.getMessage(),
                        "ERROR!",
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_OpenMenuActionPerformed

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        new CGHeader().setVisible(true);
}//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        SAXBuilder builder = new SAXBuilder();
        try {
            BRIG.PROFILE = builder.build("default-BRIG.xml");
            //Open one page.
            reload();
        } catch (JDOMException e) {
            JOptionPane.showMessageDialog(this,
                    "default-BRIG.xml is corrupt. Please check:\n" + e.getMessage(),
                    "ERROR!",
                    JOptionPane.ERROR_MESSAGE);
        } catch (IOException e) {
            JOptionPane.showMessageDialog(this,
                    "Could not read default-BRIG.xml because:\n" + e.getMessage(),
                    "ERROR!",
                    JOptionPane.ERROR_MESSAGE);
        }

    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
      new About().setVisible(true);
    }//GEN-LAST:event_jMenuItem5ActionPerformed

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
        try{
        if (BRIG.isBlastOk()) {
             Graph get = new Graph(this);
             get.setVisible(true);
        } else {
            JOptionPane.showMessageDialog(this,
                    "Could not run BLAST, please check it is installed and BRIG's BLAST location is correct",
                    "ERROR!",
                    JOptionPane.ERROR_MESSAGE);
        }
        }catch(Exception e ){
            e.printStackTrace();
            JOptionPane.showMessageDialog(this,
                    "Could not run BLAST, please check it is installed and BRIG's BLAST location is correct",
                    "ERROR!",
                    JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jMenuItem3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Object[] rem = jList1.getSelectedValues();
        for (int k = 0; k < rem.length; k++) {
            String current = rem[k].toString();
            if (current.contains("Directory: ")) {
                String get = current.replaceAll("Directory: ", "");
                List doop = BRIG.PROFILE.getRootElement().getChildren("refDir");
                for (int z = 0; z < doop.size(); z++) {
                    Element cur = ((Element) doop.get(z));
                    if (cur.getAttributeValue("location").compareTo(get) == 0) {
                        BRIG.PROFILE.getRootElement().removeContent(BRIG.PROFILE.getRootElement().indexOf(cur));
                    }
                }
            } else {
                List doop = BRIG.PROFILE.getRootElement().getChildren("refDir");
                for (int i = 0; i < doop.size(); i++) {
                    Element refDir = (Element) doop.get(i);
                    List refFiles = refDir.getChildren("refFile");
                    for(int z=0;z<refFiles.size();z++){
                        if( ((Element)refFiles.get(z)).getAttributeValue("location").compareTo(current) == 0){
                            refDir.removeContent(z);
                        }
                    }
                }
            }
        }
        save();
        reload();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
       new Options().setVisible(true);
    }//GEN-LAST:event_jMenuItem4ActionPerformed

    private void outputFolderFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_outputFolderFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_outputFolderFieldActionPerformed

    private void profileSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_profileSaveActionPerformed
        final JFileChooser fc = new JFileChooser();
        fc.showSaveDialog(this);
        if (fc.getSelectedFile() != null) {
            try {
                Document newProfile = BRIG.prepProfile(BRIG.PROFILE);
                int j = BRIG.saveXML(fc.getSelectedFile().toString(), newProfile);
                if (j == 0) {
                    JOptionPane.showMessageDialog(this,
                            "Saved!",
                            "Saved!",
                            JOptionPane.INFORMATION_MESSAGE);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_profileSaveActionPerformed

    private void jMenuItem6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem6ActionPerformed
      new QuickProfile().setVisible(true);
    }//GEN-LAST:event_jMenuItem6ActionPerformed

    private void BundleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BundleActionPerformed
        final JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int status = fc.showOpenDialog(this);
        if (fc.getSelectedFile() != null && status != JFileChooser.CANCEL_OPTION) {
            try {
            Thread execute = new Thread() {
                @Override
                public void run() {
                    try {
                        BRIG.bundleSession(fc.getSelectedFile().getAbsolutePath());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                };
                if (fc.getSelectedFile().isDirectory()) {
                    execute.start();
                } else {
                    JOptionPane.showMessageDialog(this,
                           fc.getSelectedFile().getName() + " is not a valid directory",
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }//GEN-LAST:event_BundleActionPerformed

    private void queryFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_queryFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_queryFieldActionPerformed

    /**
    * @param args the command line arguments
    */
    public static Vector SearchDir(String directory){
        File dir = new File(directory);
        FileFilter fileFilter = new FileFilter() {
            public boolean accept(File file) {
                return file.isFile();
            }
        };
        File[] files = dir.listFiles(fileFilter);
        Vector out = new Vector();
        String genbank = "gbk";
        String fasta = "fna,faa,fas";
        String embl = "embl";
        if(BRIG.PROFILE.getRootElement().getChild("brig_settings") != null){
            Element settings = BRIG.PROFILE.getRootElement().getChild("brig_settings");
            if(settings.getAttributeValue("genbankFiles") != null){
                genbank = settings.getAttributeValue("genbankFiles");
            }
            if(settings.getAttributeValue("fastaFiles") != null){
                fasta = settings.getAttributeValue("fastaFiles");
            }
            if(settings.getAttributeValue("emblFiles") != null){
                embl = settings.getAttributeValue("emblFiles");
            }
        }
        String validfiles = genbank +","+ fasta + ","+embl +",.graph";
        BRIG.Print(validfiles);
        String[] commaArray  = validfiles.split(",");
        for (int i = 0; i < files.length; i++) {
            String filename = files[i].getName();
            int no = 0;
            for (int z = 0; z < commaArray.length; z++) {
                if (filename.endsWith(commaArray[z])) {
                    no++;
                }
            }

            if (no != 0) {
                out.add(directory + File.separatorChar + filename);
            }
        }
        return out;
    }

    public void ringspoop(String file ) {
        Element newChild = new Element("ring");
        List doop = BRIG.PROFILE.getRootElement().getChildren("ring");
        // Shift all rings down one, to make room for new ring
        for (int i = 0; i < doop.size(); i++) {
            Element ccur = (Element) doop.get(i);
            int nextInt = Integer.parseInt(ccur.getAttributeValue("position"));
            if (nextInt >= (BRIG.POSITION + 1)) {
                nextInt++;
                ccur.setAttribute("position", Integer.toString(nextInt));
            }
        }
        if(doop.size() == 0 ){
            BRIG.POSITION = -1;
        }
        Color newcol = BRIG.FetchColor(BRIG.POSITION + 1);
        String col = newcol.getRed() + "," + newcol.getGreen() + "," + newcol.getBlue();
        newChild.setAttribute("colour", col);
        BRIG.Print(file);
        if( file.contains(".")){
        newChild.setAttribute("name", new File(file).getName().split("\\.")[0]);
        }else{
        newChild.setAttribute("name", new File(file).getName());
        }
        //upperInt="70" lowerInt="50" legend="no" size="30" labels="no" blastType="blastn"
        newChild.setAttribute("position", Integer.toString(BRIG.POSITION + 1));
        newChild.setAttribute("upperInt", "90");
        newChild.setAttribute("lowerInt", "70");
        newChild.setAttribute("legend", "no");
        newChild.setAttribute("size", "30");
        newChild.setAttribute("labels", "no");
        newChild.setAttribute("blastType", "blastn");
        Element child = new Element("sequence");
        child.setAttribute("location", file);
        newChild.addContent(child);
        BRIG.PROFILE.getRootElement().addContent(newChild);
        BRIG.Print(Integer.toString( BRIG.POSITION) );
        BRIG.POSITION++;
    }
        
    public void save(){
        BRIG.PROFILE.getRootElement().setAttribute("queryFile" , queryField.getText() );
        BRIG.PROFILE.getRootElement().setAttribute("blastOptions" , blastOptionField.getText() );
        BRIG.PROFILE.getRootElement().setAttribute("outputFolder" , outputFolderField.getText() );
    }

    public void reload() {
        queryField.setText(BRIG.PROFILE.getRootElement().getAttributeValue("queryFile"));
        blastOptionField.setText(BRIG.PROFILE.getRootElement().getAttributeValue("blastOptions"));
        outputFolderField.setText(BRIG.PROFILE.getRootElement().getAttributeValue("outputFolder"));
        String out = "";
        List<Element> oldRefs = BRIG.PROFILE.getRootElement().getChildren("refDir");
        List special = BRIG.PROFILE.getRootElement().getChildren("refDir");
        refModel.removeAllElements();
        for (int k = 0; k < special.size(); k++) {
            refModel.addElement("Directory: " +((Element)special.get(k)).getAttributeValue("location"));
            List sp = ((Element)special.get(k)).getChildren("refFile");
            for (int z = 0; z < sp.size(); z++) {
               refModel.addElement(((Element)sp.get(z)).getAttributeValue("location"));
            }
        }
        for (int i = 0; i < oldRefs.size(); i++) {
            out = out + "Directory: " + oldRefs.get(i).getAttributeValue("location") + "\n";
            List<Element> fil = oldRefs.get(i).getChildren("refFile");
            for (int j = 0; j < fil.size(); j++) {
                try {
                        out = out + fil.get(j).getAttributeValue("location") + "\n";
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this,
                            "Could not open " + oldRefs.get(i).getAttributeValue("location") + " because:\n" + e.getMessage(),
                            "ERROR!",
                            JOptionPane.ERROR_MESSAGE);
                }
            }
            out = out + "\n";
        }
BRIG.dumpXML("errorlog.xml",BRIG.PROFILE);
    }


    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem Bundle;
    private javax.swing.JMenuItem OpenMenu;
    private javax.swing.JMenuItem QuitMenu;
    private javax.swing.JMenuItem SaveMenu;
    private javax.swing.JTextField blastOptionField;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JList jList1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuItem jMenuItem5;
    private javax.swing.JMenuItem jMenuItem6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton nextButton;
    private javax.swing.JButton outputBrowseButton;
    private javax.swing.JTextField outputFolderField;
    private javax.swing.JMenuItem profileSave;
    private javax.swing.JButton queryBrowseButton;
    private javax.swing.JTextField queryField;
    private javax.swing.JButton refAddButton;
    private javax.swing.JButton refBrowseButton;
    private javax.swing.JCheckBox ringCheck;
    private javax.swing.JTextField sequenceAddField;
    // End of variables declaration//GEN-END:variables
}



