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

import java.awt.Color;
import java.awt.Component;
import java.awt.Rectangle;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Tom
 */
public class MatrixDialog extends javax.swing.JDialog {

   /**
    * Creates new form MatrixDialog
    * @param parent Parent des Dialogs
    * @param modal andere Fenster anklickbar
    * @param Pitches die Pitches
    * @param _title der Titel
    */
   public MatrixDialog(java.awt.Frame parent, boolean modal, int[] Pitches, String _title) {
      super(parent, modal);
      initComponents();
      tNotes.setDefaultRenderer(String.class, new CustomCellRenderer());
      
      Rectangle parentBounds = parent.getBounds();
      this.setBounds((int)(parentBounds.getWidth()/2-getBounds().getWidth()/2) + (int)parentBounds.getX(), 
                     (int)(parentBounds.getHeight()/2-getBounds().getHeight()/2) + (int)parentBounds.getY(), 
                     (int)getBounds().getWidth(), (int)getBounds().getHeight());
      
      this.setTitle(_title);
      fillTable(Pitches);
   }
   
   /**
    * CellRenderer, der die Zellen je nach Inhalt anders einfaerbt
    */
   class CustomCellRenderer extends DefaultTableCellRenderer{
      @Override
       public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,boolean hasFocus, int row, int column){
               Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
               int x = 0;
               if (!value.toString().equals(""))
               {
                  try {
                     x = Integer.valueOf(value.toString().substring(value.toString().indexOf("|")+2, value.toString().length()-1));
                  }catch (NumberFormatException nfe) {
                     ;
                  }
               }
               if (x >= 20) { //bei mehr als 20% Anteil anders einfaerben
                  cell.setBackground(Color.MAGENTA);
               }
               else if (x >= 10) { //bei mehr als 10% Anteil anders einfaerben
                  cell.setBackground(Color.green);
               }
               else if (x >= 5) { //bei mehr als 5% Anteil anders einfaerben
                  cell.setBackground(Color.yellow);
               }
               else if (!value.toString().equalsIgnoreCase("0 | 0%") 
                       && !value.toString().equalsIgnoreCase("")) {
                  cell.setBackground(Color.LIGHT_GRAY);
               }
               else
               {
                   cell.setBackground( Color.white );
               }
               return cell;

       }
   }
   
   /**
     * gibt die Anzahl der Noten des PitchArrays zurueck
     * @param Pitches ein Array mit den Pitches
     * @return Anzahl der Noten
     */
    private int getNoteCount(int[] Pitches) {
       int Count = 0;
       for (int i=0; i<Pitches.length; i++) {
          Count += Pitches[i];
       }
       return Count;
    }
   
    /**
     * fuellt die Tabelle mit der Anzahl und den Prozentwerten der Pitches
     * @param Pitches ein Array mit den Pitches
     */
   private void fillTable(int[] Pitches) {
      clearTableView();      
      DefaultTableModel tableModel = (DefaultTableModel)tNotes.getModel();
      for (int i=0; i<11; i++) {
         tableModel.addRow(new Object[]{0,"","","","","","","","","","","",""});
      }
      //Oktaven
      for (int i=-1; i<=9; i++) {
         tableModel.setValueAt(i, i+1, 0);
      }
      //Pitches
      int Count = getNoteCount(Pitches);
      this.setTitle(this.getTitle() +" Total: " +Count +" Pitches");
      int iRow = 0, iColumn = 1;
      for (int i=0; i<Pitches.length; i++) {
         tableModel.setValueAt(Pitches[i] +" | " +getPercent(Count, Pitches[i]) +"%", iRow, iColumn);
         iColumn++;
         if (iColumn > 12) {
            iColumn = 1;
            iRow++;
         }
      }
   }
   
   /**
    * liefert den Prozentanteil des Pitches am gesamten MIDI-File
    * @param count Anzahl aller Pitches
    * @param value Anzahl des Pitches
    * @return Prozentanteil des Pitches an der Gesamtheit
    */
   private int getPercent(int count, int value) {
      return (int)Math.round((100.0F * value) / count);
   }
   
   /**
     * loescht alle Zeilen der Tabelle
     */
    private void clearTableView()
    {
        DefaultTableModel tableModel = (DefaultTableModel)tNotes.getModel();
        int rowCount = tableModel.getRowCount();
        
        for(int i = 0; i < rowCount; i++)
        {
            tableModel.removeRow(0);
        }
    }

   /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
   // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
   private void initComponents() {

      jScrollPane1 = new javax.swing.JScrollPane();
      tNotes = new javax.swing.JTable();

      setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

      tNotes.setModel(new javax.swing.table.DefaultTableModel(
         new Object [][] {
            {null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null},
            {null, null, null, null, null, null, null, null, null, null, null, null, null}
         },
         new String [] {
            "Octave", "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"
         }
      ) {
         Class[] types = new Class [] {
            java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
         };
         boolean[] canEdit = new boolean [] {
            false, false, false, false, false, false, false, false, false, false, false, false, false
         };

         public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
         }

         public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
         }
      });
      tNotes.setRowSelectionAllowed(false);
      jScrollPane1.setViewportView(tNotes);

      javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
      getContentPane().setLayout(layout);
      layout.setHorizontalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGap(0, 1024, Short.MAX_VALUE)
         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
               .addContainerGap()
               .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 1004, Short.MAX_VALUE)
               .addContainerGap()))
      );
      layout.setVerticalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
         .addGap(0, 228, Short.MAX_VALUE)
         .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
               .addContainerGap()
               .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
               .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
      );

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

   /**
    * @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(MatrixDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (InstantiationException ex) {
         java.util.logging.Logger.getLogger(MatrixDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (IllegalAccessException ex) {
         java.util.logging.Logger.getLogger(MatrixDialog.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
      } catch (javax.swing.UnsupportedLookAndFeelException ex) {
         java.util.logging.Logger.getLogger(MatrixDialog.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() {
            MatrixDialog dialog = new MatrixDialog(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.JScrollPane jScrollPane1;
   private javax.swing.JTable tNotes;
   // End of variables declaration//GEN-END:variables
}
