/* 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.io.File;
import java.io.IOException;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.jdom.Element;



/**
 *
 * @author Nabil
 */
public class Three2 extends javax.swing.JFrame {
    Two parent;
    Thread ip;
    /** Creates new form Three */
    public Three2(Two par) {
        // create all components and add them
        initComponents();
        Element root = BRIG.PROFILE.getRootElement();
        String query = root.getAttributeValue("queryFile");
        setTitle(BRIG.header + " - Confirmation") ;
        outputField.setText(root.getAttributeValue("outputFolder") + BRIG.SL + BRIG.FetchFilename(query));
        if (root.getAttributeValue("outputFile") != null) {
            outputField.setText(root.getAttributeValue("outputFile"));
        }
        if (root.getAttributeValue("title") != null) {
            titleField.setText(root.getAttributeValue("title"));
        }
        if (root.getAttributeValue("blastOptions") != null) {
            blastOptions.setText(root.getAttributeValue("blastOptions"));
        }
        if (root.getAttributeValue("imageFormat") != null) {
            imageFormat.setSelectedItem( root.getAttributeValue("imageFormat"));
        }
        String text = "Your query File:\n";
        text += query + "\n";
        confirmText.setText(text);
        parent = par;
    }

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

        jLabel6 = new javax.swing.JLabel();
        submit = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        confirmText = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        previousButton = new javax.swing.JButton();
        noBlast = new javax.swing.JCheckBox();
        outputField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        queryBrowseButton = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        titleField = new javax.swing.JTextField();
        blastOptions = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        imageFormat = new javax.swing.JComboBox();

        jLabel6.setText("jLabel6");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        submit.setText("Submit");
        submit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                submitActionPerformed(evt);
            }
        });

        confirmText.setColumns(20);
        confirmText.setEditable(false);
        confirmText.setRows(5);
        jScrollPane1.setViewportView(confirmText);

        jLabel1.setText("Please confirm your configuration:");

        previousButton.setText("< Prev");
        previousButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                previousButtonActionPerformed(evt);
            }
        });

        noBlast.setText("Re-do BLAST");

        jLabel2.setText("Output file:");

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

        jLabel4.setText("Image title: ");

        jLabel5.setText("Blast options:");

        jLabel7.setText("Console:");

        jLabel3.setText("Output format:");

        imageFormat.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "jpg", "png", "svg", "svgz" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 564, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel1)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(previousButton, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(101, 101, 101)
                            .addComponent(submit, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel4)
                                        .addComponent(jLabel2)
                                        .addComponent(jLabel5))
                                    .addGap(18, 18, 18)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(titleField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 305, Short.MAX_VALUE)
                                        .addComponent(outputField, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(blastOptions, javax.swing.GroupLayout.Alignment.LEADING)))
                                .addComponent(jLabel7))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(noBlast)
                                .addComponent(queryBrowseButton)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel3)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(imageFormat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))))
        );
        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(jLabel4)
                    .addComponent(titleField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(imageFormat, 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.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(outputField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(queryBrowseButton))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(34, 34, 34)
                        .addComponent(jLabel7))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(blastOptions, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5)
                            .addComponent(noBlast))))
                .addGap(16, 16, 16)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 346, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(previousButton, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(submit, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

    private void previousButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_previousButtonActionPerformed
        BRIG.PROFILE.getRootElement().setAttribute("imageFormat", imageFormat.getSelectedItem().toString());
        BRIG.PROFILE.getRootElement().setAttribute("outputFile", outputField.getText() ) ;
        BRIG.PROFILE.getRootElement().setAttribute("title", titleField.getText() ) ;
        BRIG.PROFILE.getRootElement().setAttribute("blastOptions", blastOptions.getText() ) ;
        parent.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_previousButtonActionPerformed

    private void submitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_submitActionPerformed
        BRIG.PROFILE.getRootElement().setAttribute("outputFile", outputField.getText() ) ;
        BRIG.PROFILE.getRootElement().setAttribute("title", titleField.getText());
        BRIG.PROFILE.getRootElement().setAttribute("blastOptions", blastOptions.getText());
        BRIG.PROFILE.getRootElement().setAttribute("imageFormat", imageFormat.getSelectedItem().toString());
        String blastOpt = BRIG.BlastOption( blastOptions.getText() );
        if (blastOpt  == null ) {            
            //submit.setVisible(false);
            outputField.setEnabled(false);
            confirmText.append("--------------------------------------\n");
            ip = new Thread() {
                @Override
                public void run() {
                    try {
                        compute();
                    } catch (Exception e) {
                    }
                }
            };
            ip.start();
            
        } else {
            JOptionPane.showMessageDialog(this,
                    blastOpt ,
                    "ERROR!",
                    JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_submitActionPerformed

    private void queryBrowseButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_queryBrowseButtonActionPerformed
        File text = new File(outputField.getText());
        JFileChooser fc = new JFileChooser();
        if(text.exists()){
        if (text.getParentFile().isDirectory()) {
            fc = new JFileChooser(text.getParent());
        }
        }
        fc.showSaveDialog(this);
        if (fc.getSelectedFile() != null) {
            BRIG.PROFILE.getRootElement().setAttribute("outputFile", fc.getSelectedFile().toString());
            outputField.setText(fc.getSelectedFile().toString());
        }

}//GEN-LAST:event_queryBrowseButtonActionPerformed

    private void compute() {
        /* Parse GENBANK input file. If required.
        /* format db in scratch dir in output folder and run blast for each ring. */
        Element root = BRIG.PROFILE.getRootElement();
        String output = root.getAttributeValue("outputFolder");
        if ((new File(output)).isDirectory()) {
            new File(output + BRIG.SL + "scratch").mkdir();
            String fileName = BRIG.FetchFilename(root.getAttributeValue("queryFile"));
            boolean genbank = BRIG.isGenbank(root.getAttributeValue("queryFile"));
            boolean embl = BRIG.isEmbl(root.getAttributeValue("queryFile"));
            System.out.println(output + "?");
            if (genbank || embl) {
                try {
                    String ou = output + BRIG.SL + "scratch" + BRIG.SL + fileName;
                    String text = "";
                    if (root.getAttribute("genbankProtein") != null) {
                        root.setAttribute("queryFastaFile", ou + ".faa");
                        BRIG.PROFILE.getRootElement().setAttribute("spacer", Integer.toString(0));
                        text = BRIG.FormatGenbank(root.getAttributeValue("queryFile"),
                            fileName, output + BRIG.SL + "scratch" + BRIG.SL + fileName, embl, "T");
                    } else {
                        root.setAttribute("queryFastaFile", ou + ".fna");
                        text = BRIG.FormatGenbank(root.getAttributeValue("queryFile"),
                            fileName, output + BRIG.SL + "scratch" + BRIG.SL + fileName, embl, "F");
                    }
                    BRIG.GEN_LENGTH = BRIG.FastaLength(ou + ".fna", false);
                    BRIG.Print(text);
                } catch (Exception e) {
                    BRIG.Print("SYS_ERROR: "
                            + e.getMessage());
                    e.printStackTrace();
                }
            } else if (BRIG.PROFILE.getRootElement().getAttributeValue("spacer") != null) {
                try {

                    int space = Integer.parseInt(BRIG.PROFILE.getRootElement().getAttributeValue("spacer"));
                    String ou = output + BRIG.SL + "scratch" + BRIG.SL + "Spaced" + space + fileName;
                    String text = BRIG.formatMultiFASTA(root.getAttributeValue("queryFile"), ou,
                            space,false);
                    root.setAttribute("queryFastaFile", ou);
                    BRIG.Print(text);
                    BRIG.GEN_LENGTH = BRIG.FastaLength(root.getAttributeValue("queryFastaFile"), true);
                    BRIG.GEN_LENGTH += space + 10;
                } catch (Exception e) {
                    BRIG.Print("SYS_ERROR: "
                            + e.getMessage());
                    e.printStackTrace();
                }
            } else {
                root.setAttribute("queryFastaFile", root.getAttributeValue("queryFile"));
                try {
                    BRIG.GEN_LENGTH = BRIG.FastaLength(root.getAttributeValue("queryFastaFile"), false);
                     if( BRIG.isProteinFASTA( root.getAttributeValue("queryFastaFile")) ){
                        BRIG.GEN_LENGTH = BRIG.GEN_LENGTH *3;
                        root.setAttribute("protein","true");
                    }      
                } catch (Exception ex) {
                    BRIG.Print("SYS_ERROR: "
                            + ex.getMessage());
                }
            }
            BRIG.dumpXML("errorlog.xml",BRIG.PROFILE);
            BRIG.Print("Initializing XML output..");
            BRIG.Print(BRIG.WriteXMLLegend());
            BRIG.Print("Running BLAST...");
            int d = 0;
            if (noBlast.isSelected()) {
                d = 1;
            }
            BRIG.Print(BRIG.RunBlast(d));
            BRIG.Print("Parsing BLAST Results...");
            try {
                BRIG.Print(BRIG.ParseBlast());
            } catch (IOException ex) {
                BRIG.Print("SYS_ERROR: Could not write line: " +
                        ex.getMessage());
            }
            BRIG.Print("Rendering CGVIEW image...");
            root.setAttribute("outputFile", outputField.getText() ) ;
            BRIG.Print(BRIG.RunCGview(imageFormat.getSelectedItem().toString()));
        } else {
            BRIG.Print("SYS_ERROR: Output directory is not a valid directory. Cannot continue.\n" +
                    "Please check output location is valid directory and writeable.\n");
        }
        submit.setVisible(true);
        outputField.setEnabled(true);
    }


    


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField blastOptions;
    private javax.swing.JTextArea confirmText;
    private javax.swing.JComboBox imageFormat;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JCheckBox noBlast;
    private javax.swing.JTextField outputField;
    private javax.swing.JButton previousButton;
    private javax.swing.JButton queryBrowseButton;
    private javax.swing.JButton submit;
    private javax.swing.JTextField titleField;
    // End of variables declaration//GEN-END:variables




}
