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

import data.Beat;
import data.IScore;
import data.MultiBeat;
import data.NoteData;
import database.DatabaseInterface;
import java.awt.GridBagLayout;
import java.awt.Rectangle;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import javax.swing.table.DefaultTableModel;
import jm.music.data.Note;
import jm.music.data.Part;
import jm.music.data.Phrase;
import jm.music.data.Score;
import midi.MIDIAnalyser;
import midi.MIDIPlayer;
import midi.MidiToSheetMusic;

/**
 *
 * @author Tom
 */
public class MotifViewer extends javax.swing.JDialog {
    private String user = ""; //username
    private String pw = ""; //password
    private String url = ""; //DB-Url
    private HashMap<String, Integer> categories = new HashMap<>(); //List or categories ordered
    private Score motif = null;
    private static int PPQN = 480;
    private static int TEMPO = 120;
    
    /**
     * Creates new form MotifViewer
     */
    public MotifViewer(java.awt.Frame parent, boolean modal, String user, String pw, String url) {
        super(parent, modal);
        initComponents();
        
        this.user = user;
        this.pw = pw;
        this.url = url;
        
        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());
        
        DatabaseInterface dbi = new DatabaseInterface(user, pw, url);
        LinkedHashMap<String, Integer> cat = dbi.getCategoriesOrdered();
        Iterator it = cat.entrySet().iterator();
        while (it.hasNext()) {
           Map.Entry pairs = (Map.Entry)it.next();
           cmbCategory.addItem(pairs.getKey());
           categories.put(pairs.getKey().toString(), (int)pairs.getValue());
        }
        
        //Listbox mit Motif-IDs fuellen
        cmbCategoryActionPerformed(null);
        
        //pnlNotesheet.setLayout(new BoxLayout(pnlNotesheet, BoxLayout.Y_AXIS));
        pnlNotesheet.setLayout(new GridBagLayout());
    }
    
    /**
     * 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() {

        jLabel1 = new javax.swing.JLabel();
        btnPlayOriginal = new javax.swing.JButton();
        cmbCategory = new javax.swing.JComboBox();
        pnlNotesheet = new javax.swing.JPanel();
        btnCancel = new javax.swing.JButton();
        txtMotif = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        cmbTempo = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        cmbInteresting = new javax.swing.JComboBox();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabMotifs = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Motif Viewer");

        jLabel1.setText("Category:");

        btnPlayOriginal.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/play.png"))); // NOI18N
        btnPlayOriginal.setToolTipText("Play");
        btnPlayOriginal.setFocusable(false);
        btnPlayOriginal.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnPlayOriginal.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnPlayOriginal.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnPlayOriginalActionPerformed(evt);
            }
        });

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

        javax.swing.GroupLayout pnlNotesheetLayout = new javax.swing.GroupLayout(pnlNotesheet);
        pnlNotesheet.setLayout(pnlNotesheetLayout);
        pnlNotesheetLayout.setHorizontalGroup(
            pnlNotesheetLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        pnlNotesheetLayout.setVerticalGroup(
            pnlNotesheetLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 122, Short.MAX_VALUE)
        );

        btnCancel.setText("Close");
        btnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelActionPerformed(evt);
            }
        });

        txtMotif.setEditable(false);

        jLabel3.setText("Tempo:");

        cmbTempo.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "all", "slow", "normal", "fast" }));
        cmbTempo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbTempoActionPerformed(evt);
            }
        });

        jLabel4.setText("Interestingness Measure:");

        cmbInteresting.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "all", "less interesting", "interesting", "very interesting" }));
        cmbInteresting.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbInterestingActionPerformed(evt);
            }
        });

        tabMotifs.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Motifs"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false
            };

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

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabMotifs.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabMotifsMouseClicked(evt);
            }
        });
        tabMotifs.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tabMotifsKeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(tabMotifs);

        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()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(btnPlayOriginal, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btnCancel)
                        .addGap(32, 32, 32))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cmbCategory, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addComponent(txtMotif, javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(pnlNotesheet, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(cmbTempo, 0, 64, Short.MAX_VALUE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jLabel4)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(cmbInteresting, 0, 125, Short.MAX_VALUE)))))
                        .addGap(20, 20, 20))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(cmbCategory, 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.LEADING)
                            .addComponent(jLabel4)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel3)
                                .addComponent(cmbTempo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(cmbInteresting, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(pnlNotesheet, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(txtMotif, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnPlayOriginal, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(btnCancel, javax.swing.GroupLayout.Alignment.TRAILING)))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );

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

    /**
     * spielt das ausgewaehlte Motif ab
     * @param evt 
     */
    private void btnPlayOriginalActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnPlayOriginalActionPerformed
        if (motif != null) {
            MIDIAnalyser analyser = new MIDIAnalyser();
            IScore is = analyser.analyseTask(motif);
            MIDIPlayer.play(is);
        }
    }//GEN-LAST:event_btnPlayOriginalActionPerformed

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

    /**
     * befuellt die Listbox mit den IDs der Motive, nachdem die Combobox aktualisiert wurde
     * @param evt 
     */
    private void cmbCategoryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbCategoryActionPerformed
        if (cmbCategory.getModel().getSize() > 0){
            if (categories.containsKey(cmbCategory.getSelectedItem().toString())) {
                int cat = categories.get(cmbCategory.getSelectedItem().toString());
                int tempo = -1, interesting = -1;

                switch (cmbTempo.getSelectedItem().toString()){
                    case "all":
                        tempo = -1;
                        break;
                    case "slow":
                        tempo = 0;
                        break;
                    case "normal":
                        tempo = 1;
                        break;
                    case "fast":
                        tempo = 2;
                        break;
                }

                switch (cmbInteresting.getSelectedItem().toString()){
                    case "all":
                        interesting = -1;
                        break;
                    case "less interesting":
                        interesting = 0;
                        break;
                    case "interesting":
                        interesting = 1;
                        break;
                    case "very interesting":
                        interesting = 2;
                        break;
                }

                DatabaseInterface dbi = new DatabaseInterface(user, pw, url);
                LinkedList<Integer> lli;
                if (tempo == -1 && interesting == -1){
                    lli = dbi.getAllMotifsForCategory(cat);
                } else if (interesting == -1){ //only with tempo
                    lli = dbi.getTempoMotifsForCategory(cat, tempo);
                } else if (tempo == -1){ //only with interesting
                    lli = dbi.getInterestingMotifsForCategory(cat, interesting);
                } else { //with interesting and tempo
                    lli = dbi.getSpecificMotifsForCategory(cat, tempo, interesting);
                }
                dbi.closeConnection();

                //Tabelle loeschen
                DefaultTableModel tableModel = (DefaultTableModel)tabMotifs.getModel();
                tableModel.setRowCount(0);
                //Tabelle fuellen
                for (int x : lli){
                    tableModel.addRow(new Object[]{x});
                }
                //ersten Eintrag der Listbox auswaehlen und Ansicht aktualisieren
                if (tabMotifs.getModel().getRowCount() > 0){
                    btnPlayOriginal.setEnabled(true);
                    tabMotifs.setRowSelectionInterval(0, 0);
                    updateAll();
                } else {
                    txtMotif.setText("");
                    btnPlayOriginal.setEnabled(false);
                }
            }
        }
    }//GEN-LAST:event_cmbCategoryActionPerformed

    /**
     * befuellt die Listbox mit den IDs der Motive, nachdem die Combobox aktualisiert wurde
     * @param evt 
     */
    private void cmbTempoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTempoActionPerformed
        cmbCategoryActionPerformed(evt);
    }//GEN-LAST:event_cmbTempoActionPerformed

    /**
     * befuellt die Listbox mit den IDs der Motive, nachdem die Combobox aktualisiert wurde
     * @param evt 
     */
    private void cmbInterestingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbInterestingActionPerformed
        cmbCategoryActionPerformed(evt);
    }//GEN-LAST:event_cmbInterestingActionPerformed

    private void tabMotifsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabMotifsMouseClicked
        updateAll();
    }//GEN-LAST:event_tabMotifsMouseClicked

    private void tabMotifsKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tabMotifsKeyReleased
        //Arrow Up or Arrow Down
        if (evt.getKeyCode() == 38 || evt.getKeyCode() == 40){
            updateAll();
        }
    }//GEN-LAST:event_tabMotifsKeyReleased

    /**
     * aktualisiert das Notesheet und erstellt einen neuen MIDI-Score des Motifs
     * des neu ausgewaehlten Eintrags
     */
    private void updateAll(){
        if (tabMotifs.getSelectedRow() != -1){
            DatabaseInterface dbI = new DatabaseInterface(user, pw, url);

            if (dbI.isPolyphonMotif((int)tabMotifs.getModel().getValueAt(tabMotifs.getSelectedRow(), 0))){ //polyphon
                MultiBeat mb = dbI.getPolyphonMotif((int)tabMotifs.getModel().getValueAt(tabMotifs.getSelectedRow(), 0));
                txtMotif.setText(mb.toString());
                motif = getPolyphonScore(mb);
            } else { //monophon
                Beat b = dbI.getMonophonMotif((int)tabMotifs.getModel().getValueAt(tabMotifs.getSelectedRow(), 0));
                txtMotif.setText(b.toString());
                motif = getMonophonScore(b);
            }
            int[] iArr = dbI.getMotifNumeratorAndDenominator((int)tabMotifs.getModel().getValueAt(tabMotifs.getSelectedRow(), 0));
            String s = dbI.getMotifKey((int)tabMotifs.getModel().getValueAt(tabMotifs.getSelectedRow(), 0));
            boolean Major = false;
            if (s.substring(s.indexOf(" ")+1).equalsIgnoreCase("Major")){
                Major = true;
            }
            s = s.substring(0,s.indexOf(" "));
            
            dbI.closeConnection();

            if (motif != null){
                MidiToSheetMusic mtsm = new MidiToSheetMusic(motif, false, iArr[0], iArr[1], s, Major);
                pnlNotesheet.removeAll();
                pnlNotesheet.add(mtsm.getNoteSheetJScoreComponent());
                pnlNotesheet.repaint();
            }
            this.revalidate();
        }
    }
    
    /**
     * liefert einen monophonen Score bestehend aus den Noten des uebergebenen Takts
     * @param b ein monophoner Takt
     * @return MIDI-Score
     */
    private Score getMonophonScore(Beat b){
        Phrase ph = new Phrase(0.0);
        for (NoteData nd : b.getBeat()){
            Note n = new Note(nd.getPitch(), nd.getQuantizedDuration()*PPQN);
            n.setDuration(nd.getQuantizedDuration());
            n.setDynamic(100);
            ph.add(n);
        }

        Score s = new Score("pbmc-composition",TEMPO);
        s.setPPQN(PPQN);
        
        Part p = new Part("Part 0", b.getInstrument());
        p.setChannel(0);
        p.addPhrase(ph);
        s.addPart(p);
        
        return s;
    }
    
    /**
     * liefert einen polyphonen Score bestehend aus den Noten des uebergebenen Takts
     * @param mb ein polyphoner Takt
     * @return MIDI-Score
     */
    private Score getPolyphonScore(MultiBeat mb){
        NoteData[][] ndarr = mb.getBeat();
        Part p = new Part("Part 0", mb.getInstrument());
        p.setChannel(0);
        
        for (int i=0; i<ndarr.length; i++){
            Phrase ph = new Phrase(0.0);
            for (int j=0; j<ndarr[i].length; j++){
                Note n = new Note(ndarr[i][j].getPitch(), ndarr[i][j].getQuantizedDuration()*PPQN);
                n.setDuration(ndarr[i][j].getQuantizedDuration());
                n.setDynamic(100);
                ph.add(n);
            }
            p.addPhrase(ph);
        }
        
        Score s = new Score("pbmc-composition",TEMPO);
        s.setPPQN(PPQN);
        s.addPart(p);
        
        return s;
    }
    
    /**
     * @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(MotifViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MotifViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MotifViewer.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MotifViewer.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() {
                MotifViewer dialog = new MotifViewer(new javax.swing.JFrame(), true, null, 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 btnCancel;
    private javax.swing.JButton btnPlayOriginal;
    private javax.swing.JComboBox cmbCategory;
    private javax.swing.JComboBox cmbInteresting;
    private javax.swing.JComboBox cmbTempo;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JPanel pnlNotesheet;
    private javax.swing.JTable tabMotifs;
    private javax.swing.JTextField txtMotif;
    // End of variables declaration//GEN-END:variables
}
