/*
 * iReport - Visual Designer for JasperReports.
 * Copyright (C) 2002 - 2009 Jaspersoft Corporation. All rights reserved.
 * http://www.jaspersoft.com
 *
 * Unless you have purchased a commercial license agreement from Jaspersoft,
 * the following license terms apply:
 *
 * This program is part of iReport.
 *
 * iReport is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * iReport 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with iReport. If not, see <http://www.gnu.org/licenses/>.
 */
package com.jaspersoft.ireport.designer.sheet.editors;

import com.jaspersoft.ireport.designer.sheet.Tag;
import com.jaspersoft.ireport.designer.utils.Misc;
import com.jaspersoft.ireport.locale.I18n;
import java.awt.Component;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyEditor;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultListSelectionModel;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import net.sf.jasperreports.engine.TabStop;
import net.sf.jasperreports.engine.type.TabStopAlignEnum;
import org.openide.explorer.propertysheet.PropertyEnv;

/**
 *
 * @author  gtoffoli
 */
public class JRTabStopsPropertyCustomEditor extends javax.swing.JPanel implements PropertyChangeListener {
    
    private PropertyEnv env;

    private PropertyEditor editor;
    
    
    public JRTabStopsPropertyCustomEditor (Object value, PropertyEditor editor, PropertyEnv env) {
        this.env = env;
        this.editor = editor;
        this.env.setState(PropertyEnv.STATE_NEEDS_VALIDATION);
        this.env.addPropertyChangeListener(this);

        initComponents();

        Tag[] tags = new Tag[] {
                    new Tag( TabStopAlignEnum.LEFT.getValueByte(), I18n.getString("AbstractStyleNode.Property.Left")  ),
                    new Tag( TabStopAlignEnum.CENTER.getValueByte(), I18n.getString("AbstractStyleNode.Property.Center")  ),
                    new Tag( TabStopAlignEnum.RIGHT.getValueByte(), I18n.getString("AbstractStyleNode.Property.Right")  )
                    };

        jTableProperties.getColumnModel().getColumn(1).setCellEditor(new ComboBoxEditor(tags));

        jTableProperties.getColumnModel().getColumn(1).setCellRenderer(new ComboBoxRenderer(tags));

        DefaultListSelectionModel dlsm =  (DefaultListSelectionModel)this.jTableProperties.getSelectionModel();
        dlsm.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e)  {
                jTablePropertiesListSelectionValueChanged(e);
            }
        });  
        
        if (value instanceof List && value != null)
        {
            setTabStops((List)value);
        }
    }


    
    /** 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.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanelFields = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTableProperties = new javax.swing.JTable();
        jPanelButtons2 = new javax.swing.JPanel();
        jButtonNewProperty = new javax.swing.JButton();
        jButtonDeleteProperty = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();

        jPanelFields.setLayout(new java.awt.BorderLayout());

        jScrollPane3.setBackground(new java.awt.Color(255, 255, 255));
        jScrollPane3.setPreferredSize(new java.awt.Dimension(32767, 32767));
        jScrollPane3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jScrollPane3MouseClicked(evt);
            }
        });

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

            },
            new String [] {
                "Position", "Alignment"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Byte.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTableProperties.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTablePropertiesMouseClicked(evt);
            }
        });
        jScrollPane3.setViewportView(jTableProperties);

        jPanelFields.add(jScrollPane3, java.awt.BorderLayout.CENTER);

        jPanelButtons2.setMinimumSize(new java.awt.Dimension(100, 10));
        jPanelButtons2.setPreferredSize(new java.awt.Dimension(100, 100));
        jPanelButtons2.setLayout(new java.awt.GridBagLayout());

        jButtonNewProperty.setText(org.openide.util.NbBundle.getMessage(JRTabStopsPropertyCustomEditor.class, "JRTabStopsPropertyCustomEditor.jButtonNewProperty.text")); // NOI18N
        jButtonNewProperty.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNewPropertyActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(5, 4, 0, 4);
        jPanelButtons2.add(jButtonNewProperty, gridBagConstraints);

        jButtonDeleteProperty.setText(org.openide.util.NbBundle.getMessage(JRTabStopsPropertyCustomEditor.class, "JRTabStopsPropertyCustomEditor.jButtonDeleteProperty.text")); // NOI18N
        jButtonDeleteProperty.setEnabled(false);
        jButtonDeleteProperty.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeletePropertyActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        jPanelButtons2.add(jButtonDeleteProperty, gridBagConstraints);

        jPanel1.setLayout(new java.awt.BorderLayout());
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.weighty = 1.0;
        jPanelButtons2.add(jPanel1, gridBagConstraints);

        jPanelFields.add(jPanelButtons2, java.awt.BorderLayout.EAST);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 440, Short.MAX_VALUE)
            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(4, 4, 4)
                    .add(jPanelFields, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 432, Short.MAX_VALUE)
                    .add(4, 4, 4)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 344, Short.MAX_VALUE)
            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(4, 4, 4)
                    .add(jPanelFields, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 336, Short.MAX_VALUE)
                    .add(4, 4, 4)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jTablePropertiesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTablePropertiesMouseClicked
        
    }//GEN-LAST:event_jTablePropertiesMouseClicked

    private void jScrollPane3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jScrollPane3MouseClicked
        // Add your handling code here:
    }//GEN-LAST:event_jScrollPane3MouseClicked

    private void jButtonNewPropertyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNewPropertyActionPerformed
        
        DefaultTableModel dtm = (DefaultTableModel)jTableProperties.getModel();
        
        Vector row = new Vector();
        row.addElement(0);
        row.addElement( TabStopAlignEnum.LEFT.getValue() );
        dtm.addRow(row);
        

    }//GEN-LAST:event_jButtonNewPropertyActionPerformed

    private void jButtonDeletePropertyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDeletePropertyActionPerformed
        int[]  rows= jTableProperties.getSelectedRows();
        DefaultTableModel dtm = (DefaultTableModel)jTableProperties.getModel();
        for (int i=rows.length-1; i>=0; --i) {
            dtm.removeRow(rows[i]);  //jTableProperties.convertRowIndexToModel(rows[i])
        }
    }//GEN-LAST:event_jButtonDeletePropertyActionPerformed
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonDeleteProperty;
    private javax.swing.JButton jButtonNewProperty;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanelButtons2;
    private javax.swing.JPanel jPanelFields;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTableProperties;
    // End of variables declaration//GEN-END:variables
    


     public void setTabStops(List<TabStop> tabStops)
     {
         DefaultTableModel dtm = (DefaultTableModel)jTableProperties.getModel();
         dtm.setRowCount(0);
        
         for (TabStop tabStop : tabStops)
         {
            Vector row = new Vector();
            row.addElement( tabStop.getPosition());
            row.addElement( tabStop.getAlignment().getValueByte() );
            dtm.addRow(row);  
         }
         
     }
     
    public List getTabStops() {


        List<TabStop> tabStops = new ArrayList<TabStop>();

        DefaultTableModel dtm = (DefaultTableModel)jTableProperties.getModel();
        for (int i=0; i<dtm.getRowCount(); ++i)
        {
            if (dtm.getValueAt(i, 0) != null)
            {
                tabStops.add( new TabStop( (Integer)dtm.getValueAt(i, 0)  , TabStopAlignEnum.getByValue( (Byte)dtm.getValueAt(i, 1)  )));
            }
        }
        
        return tabStops;
    }
    
    
    /**
    * @return Returns the property value that is result of the CustomPropertyEditor.
    * @exception InvalidStateException when the custom property editor does not represent valid property value
    *            (and thus it should not be set)
    */
    private Object getPropertyValue () throws IllegalStateException {
        return getTabStops();
    }



    public void propertyChange(PropertyChangeEvent evt) {
        if (PropertyEnv.PROP_STATE.equals(evt.getPropertyName()) && evt.getNewValue() == PropertyEnv.STATE_VALID) {
            editor.setValue(getPropertyValue());
        }
    }
    
    public void jTablePropertiesListSelectionValueChanged(javax.swing.event.ListSelectionEvent e)
    {
         if (this.jTableProperties.getSelectedRowCount() > 0) {
            this.jButtonDeleteProperty.setEnabled(true);
        }
        else {
            this.jButtonDeleteProperty.setEnabled(false);
        }
    }
    
}


class ComboBoxRenderer extends JComboBox implements TableCellRenderer {
    public ComboBoxRenderer(Tag[] items) {
        super(items);
    }

    public Component getTableCellRendererComponent(JTable table, Object value,
            boolean isSelected, boolean hasFocus, int row, int column) {
        if (isSelected) {
            setForeground(table.getSelectionForeground());
            super.setBackground(table.getSelectionBackground());
        } else {
            setForeground(table.getForeground());
            setBackground(table.getBackground());
        }

        // Select the current value

        // set the correct selected value...
        Misc.setComboBoxTag(true, value, this);

        return this;
    }
}

class ComboBoxEditor extends DefaultCellEditor {
    public ComboBoxEditor(Tag[] items) {
        super(new JComboBox(items));
    }

    @Override
    public Object getCellEditorValue() {
        Tag t = (Tag) super.getCellEditorValue();
        if (t==null) return t;
        return t.getValue();
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        JComboBox box = (JComboBox) super.getTableCellEditorComponent(table, value, isSelected, row, column);

        // set the correct selected value...
        Misc.setComboBoxTag(true, value, box);
        
        return box;
    }



}
