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

/*
 * MoleculeOutputTable.java
 *
 * Created on Mar 5, 2011, 10:02:17 PM
 */
package com.epam.indigo.controls;

import com.epam.indigo.IndigoObject;
import java.awt.Component;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;

/**
 *
 * @author achurinov
 */
public class MoleculeOutputTable extends TitledBorderPanel
{
   protected ArrayList<? extends RenderableObjectWithId> _molecules;
   boolean reactions = false;

   public MoleculeOutputTable ()
   {
      initComponents();
      save_reactions.setVisible(false);
   }

   public void setIdColumnCount (int count)
   {
      molecules_table.setIdColumnCount(count);
   }
   
   public int getIdColumnCount ()
   {
      return molecules_table.getIdColumnCount();
   }
   
    public void setReactionsContentType (boolean reactions)
    {
        this.reactions = reactions;
        if (reactions)
        {
            molecules_table.setEntityColumnLabel("Reactions");
            save_button.setText("Save products");
            save_reactions.setText("Save reactions");
            save_reactions.setVisible(true);
        }
        else
        {
            molecules_table.setEntityColumnLabel("Molecules");
            save_reactions.setVisible(false);
            save_button.setText("Save");
        }
    }

    public boolean getReactionsContentType ()
    {
        return reactions;
    }
    
   /** 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() {

        molecules_table = new com.epam.indigo.controls.MoleculeTableWithIdPanel();
        jPanel1 = new javax.swing.JPanel();
        save_button = new javax.swing.JButton();
        save_reactions = new javax.swing.JButton();

        setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.PAGE_AXIS));

        molecules_table.addTableCellMouseListener(new com.epam.indigo.controls.TableCellMouseListener() {
            public void cellMouseDoubleClick(com.epam.indigo.controls.TableCellMouseEvent evt) {
                molecules_tableCellMouseDoubleClick(evt);
            }
            public void cellShowPopupMenu(com.epam.indigo.controls.TableCellMouseEvent evt) {
                molecules_tableCellShowPopupMenu(evt);
            }
        });
        add(molecules_table);

        jPanel1.setLayout(new javax.swing.BoxLayout(jPanel1, javax.swing.BoxLayout.LINE_AXIS));

        save_button.setText("Save");
        save_button.setMargin(new java.awt.Insets(2, 30, 2, 30));
        save_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                save_buttonActionPerformed(evt);
            }
        });
        jPanel1.add(save_button);

        save_reactions.setText("Save reactions");
        save_reactions.setMargin(new java.awt.Insets(2, 30, 2, 30));
        save_reactions.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                save_reactionsActionPerformed(evt);
            }
        });
        jPanel1.add(save_reactions);

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

    private void molecules_tableCellMouseDoubleClick (com.epam.indigo.controls.TableCellMouseEvent evt)//GEN-FIRST:event_molecules_tableCellMouseDoubleClick
    {//GEN-HEADEREND:event_molecules_tableCellMouseDoubleClick
      RenderableObjectWithId item = _molecules.get(evt.row);
      showMolecule(item);
    }
   
    protected void showMolecule(RenderableObjectWithId item) {
        Frame parent = (Frame) getTopLevelAncestor();
        IndigoObject obj = item.getRenderableObject();
        // Show details window for single molecule
        SingleIndigoObjectWindow details = new SingleIndigoObjectWindow(parent,
                obj, item.getIndigoRenderer(), reactions);
        if (item.getErrorMessageToRender() != null) {
            details.setInformationMessage(item.getErrorMessageToRender());
        }
        String title = item.getId(0);
        details.setTitle(title);
        details.setVisible(true);
    }//GEN-LAST:event_molecules_tableCellMouseDoubleClick

    protected void addAdditionalItemsToPopup (JPopupMenu _popup_menu, TableCellMouseEvent evt)
    {
    }
    
    private void molecules_tableCellShowPopupMenu (com.epam.indigo.controls.TableCellMouseEvent evt)//GEN-FIRST:event_molecules_tableCellShowPopupMenu
    {//GEN-HEADEREND:event_molecules_tableCellShowPopupMenu
      final TableCellMouseEvent evt_final = evt;
      
      JPopupMenu _popup_menu = new JPopupMenu();
      JMenuItem show_mi = new JMenuItem("Open in a new window");
      show_mi.addActionListener(new ActionListener()
      {
         public void actionPerformed (ActionEvent e)
         {
            molecules_tableCellMouseDoubleClick(evt_final);
         }
      });
      _popup_menu.add(show_mi);
      addAdditionalItemsToPopup(_popup_menu, evt);
      
      _popup_menu.show((Component)evt.mouse_event.getSource(), evt.mouse_event.getX(), evt.mouse_event.getY());
    }//GEN-LAST:event_molecules_tableCellShowPopupMenu

    private void saveResults (boolean products)
    {
       // TODO: save with progress bar!
       // TODO: if no properties then add ID
       if (_molecules.isEmpty())
       {
          JOptionPane.showMessageDialog(this, "Set is empty");
          return;
       }
       MolSaver saver = new MolSaver(Global.indigo);
       if (products)
       {
        saver.addExtension("sdf", "sd");
        saver.addExtension("smi");
        saver.addExtension("cml");
        if (reactions)
            saver.setSaveReactionProducts(true);
       }
       else
       {
        saver.addExtension("rdf");
        saver.addExtension("smi");
       }
       saver.saveMols(_molecules);

       ArrayList<RenderableObject> invalid = saver.getInvalidObjects();
       if (!invalid.isEmpty())
       {
          StringBuilder error_messages = new StringBuilder();
          for (RenderableObject abstract_obj : invalid)
          {
             RenderableObjectWithId obj = (RenderableObjectWithId)abstract_obj;
             error_messages.append(String.format("%s: %s\n",
                     obj.getId(0), obj.getErrorMessageToRender()));
          }

          Frame parent = (Frame)getTopLevelAncestor();
          String message = String.format("Cannot save the following entity:\n%s", 
                  error_messages.toString());
          MessageBox.show(parent, message, "Some entities cannot be saved", MessageBox.ICON_WARNING);
       }
    }
    
    private void save_buttonActionPerformed (java.awt.event.ActionEvent evt)//GEN-FIRST:event_save_buttonActionPerformed
    {//GEN-HEADEREND:event_save_buttonActionPerformed
        saveResults(true);
    }//GEN-LAST:event_save_buttonActionPerformed

    private void save_reactionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_save_reactionsActionPerformed
        saveResults(false);
    }//GEN-LAST:event_save_reactionsActionPerformed

   public void clear ()
   {
      molecules_table.clear();
   }

   public void setMolecules (ArrayList<? extends RenderableObjectWithId> molecules)
   {
      _molecules = molecules;
      molecules_table.setObjects(_molecules);
      
      int errors_count = 0;
      for (RenderableObjectWithId obj: molecules)
         if (obj.getErrorMessageToRender() != null)
            errors_count++;
      
      StringBuilder subtitle = new StringBuilder();
      subtitle.append(String.format(": %d molecule%s", molecules.size(),
              molecules.size() != 1 ? "s" : ""));
      if (errors_count != 0)
         subtitle.append(String.format(" (with %d not valid)", errors_count));
      setSubtitle(subtitle.toString());
   }

   public void setRowHeight (int height)
   {
      molecules_table.setRowHeight(height);
   }
   
   public int getRowHeight ()
   {
      return molecules_table.getRowHeight();
   }
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private com.epam.indigo.controls.MoleculeTableWithIdPanel molecules_table;
    private javax.swing.JButton save_button;
    private javax.swing.JButton save_reactions;
    // End of variables declaration//GEN-END:variables
}
