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

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JList;
import org.cobi.kgg.ui.GlobalManager;
import org.cobi.util.plot.MatrixBoxPainter;
import org.cobi.util.text.LocalString;
import org.openide.DialogDisplayer;
import org.openide.ErrorManager;
import org.openide.NotifyDescriptor;
import org.openide.util.Exceptions;
import org.openide.util.ImageUtilities;

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

    DefaultComboBoxModel<String> pvalueTitleBox = new DefaultComboBoxModel<String>();
    double[][] corrMatrix = null;
    String[] traitIDsArray = null;
    JList<String> buildAnaDialogList = null;
    List<Double> corrList;
//    Image ige=null;
    BufferedImage ige = null;

    /**
     * Creates new form CorrelationMatrixDefJDialog
     */
    public CorrelationMatrixDefJDialog(java.awt.Frame parent, boolean modal, JList<String> jlist, List<Double> corMatrix) {
        super(parent, modal);
        initComponents();
        setIconImage(ImageUtilities.loadImage("org/cobi/kgg/ui/png/16x16/logo1.png"));
        this.corrList = corMatrix;
        this.buildAnaDialogList = jlist;
    }

    public void updateTiteBox(DefaultComboBoxModel<String> pvalueTitleBox1) {
        pvalueTitleBox.removeAllElements();
        int size = pvalueTitleBox1.getSize();
        for (int i = 0; i < size; i++) {
            pvalueTitleBox.addElement(pvalueTitleBox1.getElementAt(i));
        }

    }

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

        jButton11 = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        paintPanel = new javax.swing.JPanel();
        figureLabel = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        titleList = new javax.swing.JList<String>();
        jLabel1 = new javax.swing.JLabel();
        matrixFilePathTextField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(org.openide.util.NbBundle.getMessage(CorrelationMatrixDefJDialog.class, "CorrelationMatrixDefJDialog.title")); // NOI18N
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

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

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

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

        paintPanel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 204, 51), 1, true));

        org.openide.awt.Mnemonics.setLocalizedText(figureLabel, org.openide.util.NbBundle.getMessage(CorrelationMatrixDefJDialog.class, "CorrelationMatrixDefJDialog.figureLabel.text")); // NOI18N
        figureLabel.setDoubleBuffered(true);

        javax.swing.GroupLayout paintPanelLayout = new javax.swing.GroupLayout(paintPanel);
        paintPanel.setLayout(paintPanelLayout);
        paintPanelLayout.setHorizontalGroup(
            paintPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(figureLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 566, Short.MAX_VALUE)
        );
        paintPanelLayout.setVerticalGroup(
            paintPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(figureLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
        );

        jLabel16.setBackground(new java.awt.Color(204, 255, 204));
        org.openide.awt.Mnemonics.setLocalizedText(jLabel16, org.openide.util.NbBundle.getMessage(CorrelationMatrixDefJDialog.class, "CorrelationMatrixDefJDialog.jLabel16.text")); // NOI18N

        titleList.setModel(pvalueTitleBox);
        jScrollPane3.setViewportView(titleList);

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

        matrixFilePathTextField.setToolTipText(org.openide.util.NbBundle.getMessage(CorrelationMatrixDefJDialog.class, "CorrelationMatrixDefJDialog.matrixFilePathTextField.toolTipText")); // NOI18N

        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(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(matrixFilePathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 429, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButton11, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(cancelButton)
                                .addGap(26, 26, 26))))
                    .addComponent(paintPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                            .addComponent(jLabel1)
                            .addComponent(matrixFilePathTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton11))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(paintPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel16, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane3)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(cancelButton)))
        );

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

    private void jButton11ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton11ActionPerformed
        String path = null;
        JFileChooser fDialog = null;
        if ((GlobalManager.lastAccessedPath != null) && (GlobalManager.lastAccessedPath.trim().length() > 0)) {
            fDialog = new JFileChooser(GlobalManager.lastAccessedPath);
        } else {
            fDialog = new JFileChooser();
        }

        fDialog.setDialogTitle("Choose a file folder with mulitple Haplotype files");

        int result = fDialog.showOpenDialog(this);
        if (result == JFileChooser.APPROVE_OPTION) {
            GlobalManager.lastAccessedPath = fDialog.getSelectedFile().getPath();
            GlobalManager.lastAccessedPath = GlobalManager.lastAccessedPath.substring(0, GlobalManager.lastAccessedPath.lastIndexOf(File.separator) + 1);

            try {
                File file = fDialog.getSelectedFile();
                path = file.getCanonicalPath();
                matrixFilePathTextField.setText(path);
                readCorrelationMatrix(path);

                //JOptionPane.showMessageDialog(this, FILE_OPEN_APPROVED, "Message", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception ex) {
                ErrorManager.getDefault().notify(ex);
            }
        } else {
            //JOptionPane.showMessageDialog(this, FILE_OPEN_CANCELLED, "Message", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_jButton11ActionPerformed

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

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        int[] indexes = titleList.getSelectedIndices();
        Set<String> strList = new HashSet<String>();
        for (int i = 0; i < indexes.length; i++) {
            strList.add(pvalueTitleBox.getElementAt(indexes[i]));
        }

        if (strList.size() != traitIDsArray.length) {
            String info = "Please choose the same number of p value sources as indicated by the loaded correlation matrix file!";
            NotifyDescriptor nd = new NotifyDescriptor.Message(info, NotifyDescriptor.ERROR_MESSAGE);
            DialogDisplayer.getDefault().notifyLater(nd);
            return;
        }

        for (int i = 0; i < traitIDsArray.length; i++) {
            if (!strList.contains(traitIDsArray[i])) {
                String info = "The loaded trait name " + traitIDsArray[i] + " does not match any selected p value source names!!";
                NotifyDescriptor nd = new NotifyDescriptor.Message(info, NotifyDescriptor.ERROR_MESSAGE);
                DialogDisplayer.getDefault().notifyLater(nd);
                return;
            }
        }
        this.setVisible(false);
        buildAnaDialogList.setSelectedIndices(indexes);
        corrList.clear();
        int rowNum = corrMatrix.length;
        int colNum = corrMatrix[0].length;
        for (int i = 0; i < rowNum; i++) {
            for (int j = 0; j < colNum; j++) {
                corrList.add(corrMatrix[i][j]);
            }
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
        /*
         try {
         if (corrMatrix != null) {
         MatrixBoxPainter boxPainter = new MatrixBoxPainter(paintPanel.getWidth(), paintPanel.getHeight());
              
         boxPainter.setMaxValue(1);
         boxPainter.setMinValue(0);

         // File outputPath = new File(imgFolder.getCanonicalPath() + File.separator + "MatrixImageRelat.png");
         boxPainter.drawMatrixPicture(corrMatrix, traitIDsArray, null, null);
         // URL pageUrl = new URL("file:///" + outputPath.getCanonicalPath());
         //figureLabel = new JLabel(new ImageIcon(ImageIO.read(pageUrl)));

         figureLabel.setIcon(new ImageIcon(boxPainter.getImage()));
         paintPanel.revalidate();
         }

         } catch (Exception ex) {
         ErrorManager.getDefault().notify(ex);
         }
         */
        try {
            // TODO add your handling code here:
            if (ige == null) {
                return;
            }
          
            MatrixBoxPainter boxPainter = new MatrixBoxPainter(figureLabel.getVisibleRect().width, figureLabel.getVisibleRect().height);
            //System.out.println(figureLabel.getWidth() + "\t" + figureLabel.getHeight());
            boxPainter.drawMatrixBox(corrMatrix, traitIDsArray, null, null);
            figureLabel.setIcon(new ImageIcon(boxPainter.getImage()));
            paintPanel.revalidate();
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        }        
        
        
    }//GEN-LAST:event_formComponentResized

    public void readCorrelationMatrix(String filePath) throws Exception {
        BufferedReader br = new BufferedReader(new FileReader(filePath));
        String line = null;
        int colNum = -1;

        line = br.readLine();
        line = line.trim();
        StringTokenizer tokenizer = new StringTokenizer(line);

        List<String> traitIDs = new ArrayList<String>();
        colNum = 0;
        while (tokenizer.hasMoreTokens()) {
            traitIDs.add(tokenizer.nextToken().trim());
        }
        colNum = traitIDs.size();
        corrMatrix = new double[colNum][colNum];
        int rowNum = 0;
        String tmpStr = null;
        while ((line = br.readLine()) != null) {
            line = line.trim();
            if (line.trim().length() == 0) {
                continue;
            }
            tokenizer = new StringTokenizer(line);

            colNum = 0;

            while (tokenizer.hasMoreTokens()) {
                tmpStr = tokenizer.nextToken().trim();
                if (LocalString.isNumeric(tmpStr)) {
                    corrMatrix[rowNum][colNum] = Math.abs(Double.parseDouble(tmpStr));
                    colNum++;
                }

            }
            rowNum++;
        }
        br.close();

        traitIDsArray = traitIDs.toArray(new String[0]);
        MatrixBoxPainter boxPainter = new MatrixBoxPainter(figureLabel.getWidth(), figureLabel.getHeight());

        boxPainter.setMaxValue(1);
        boxPainter.setMinValue(0);

        // File outputPath = new File(imgFolder.getCanonicalPath() + File.separator + "MatrixImageRelat.png");
        boxPainter.drawMatrixBox(corrMatrix, traitIDsArray, null, null);
        // URL pageUrl = new URL("file:///" + outputPath.getCanonicalPath());
        //figureLabel = new JLabel(new ImageIcon(ImageIO.read(pageUrl)));
//        boxPainter.drawMatrixPicture(corrMatrix, traitIDsArray);
//        bge=boxPainter.getImage();
        ige = boxPainter.getImage();
//        figureLabel.setIcon(new ImageIcon(boxPainter.getImage()));
        figureLabel.setIcon(new ImageIcon(ige));
        paintPanel.revalidate();
    }

    /**
     * @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(CorrelationMatrixDefJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CorrelationMatrixDefJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CorrelationMatrixDefJDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CorrelationMatrixDefJDialog.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() {
                CorrelationMatrixDefJDialog dialog = new CorrelationMatrixDefJDialog(new javax.swing.JFrame(), true, null, null);
                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 cancelButton;
    private javax.swing.JLabel figureLabel;
    private javax.swing.JButton jButton11;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextField matrixFilePathTextField;
    private javax.swing.JPanel paintPanel;
    private javax.swing.JList<String> titleList;
    // End of variables declaration//GEN-END:variables
}
