/*
 * iReport - Visual Designer for JasperReports.
 * Copyright (C) 2002 - 2013 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.jasperserver.ui.inputcontrols.impl;

import com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.InputControlQueryDataRow;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author  gtoffoli
 */
public class TableListInputControlUI extends javax.swing.JPanel implements InputControlUI {

    private List<ActionListener> listeners = new ArrayList<ActionListener>();

    private java.util.List itemValues = new java.util.ArrayList();
    
    /** Creates new form BasicInputControlUI */
    public TableListInputControlUI() {
        initComponents();
        
        jTable1.getParent().setBackground( jTable1.getBackground() );

        jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                if (e.getValueIsAdjusting() == true) return;
                for (ActionListener listener : listeners)
                {
                    try {
                        listener.actionPerformed(new ActionEvent(this, 0, ""));
                    } catch (Exception ex) {}
                }
            }
        });
    }
    
    public Object getValue()
    {
        java.util.List list = new java.util.ArrayList();
        
        int[] selection = jTable1.getSelectedRows();
        for (int i=0; i<selection.length; ++i)
        {
            list.add(itemValues.get(selection[i]) );
        }
        
        return list;
    }
    
    public void setValue(Object v)
    {
        if (v != null && v instanceof Collection)
        {
            jTable1.clearSelection();
            Iterator values = ((Collection)v).iterator();
            while (values.hasNext())
            {
                Object val = values.next();
                int row = itemValues.indexOf( val );
                if ( row >= 0)
                {
                    jTable1.addRowSelectionInterval(row, row);
                }
            }
        }
    }
    
    /** 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;

        buttonGroup1 = new javax.swing.ButtonGroup();
        jLabelName = new javax.swing.JLabel();
        jPanelList = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setLayout(new java.awt.GridBagLayout());

        setMinimumSize(new java.awt.Dimension(42, 150));
        setPreferredSize(new java.awt.Dimension(250, 150));
        jLabelName.setText("jLabel1");
        jLabelName.setMinimumSize(new java.awt.Dimension(34, 14));
        jLabelName.setPreferredSize(new java.awt.Dimension(34, 14));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
        add(jLabelName, gridBagConstraints);

        jPanelList.setLayout(new java.awt.GridBagLayout());

        jPanelList.setBackground(new java.awt.Color(255, 255, 255));
        jScrollPane1.setBackground(new java.awt.Color(255, 255, 255));
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null}
            },
            new String [] {
                "Title 1"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setGridColor(new java.awt.Color(255, 255, 255));
        jTable1.setIntercellSpacing(new java.awt.Dimension(0, 0));
        jTable1.setOpaque(false);
        jTable1.setRowMargin(0);
        jTable1.setShowHorizontalLines(false);
        jTable1.setShowVerticalLines(false);
        jTable1.setTableHeader(null);
        jScrollPane1.setViewportView(jTable1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        jPanelList.add(jScrollPane1, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(2, 14, 4, 4);
        add(jPanelList, gridBagConstraints);

    }// </editor-fold>//GEN-END:initComponents
    
    public void setLabel(String lbl)
    {
        this.jLabelName.setText(lbl);
    }
    
    /**
     *  Expected a list of InputControlQueryDataRow
     */
    public void setHistory(java.util.List values){
        
        if (values == null) return;
        
        int maxColumns = 1;
        
        Object[][] rowValues = new Object[ values.size()][];
        for (int i=0; i<values.size(); ++i)
        {
            InputControlQueryDataRow qd =  (InputControlQueryDataRow)values.get(i);
            maxColumns = (qd.getColumnValues().size()>maxColumns) ? qd.getColumnValues().size() : maxColumns;
        
            rowValues[i] = new Object[ qd.getColumnValues().size() ];
            for (int k=0; k<qd.getColumnValues().size(); k++)
            {
                rowValues[i][k] = qd.getColumnValues().get(k);
            }
            itemValues.add( qd.getValue() );
        }
        
        String[] columnNames = new String[maxColumns];
        for (int i=0; i<maxColumns; ++i) {
            columnNames[i] = "" + i;
        }
        
        DefaultTableModel dtm = new javax.swing.table.DefaultTableModel(rowValues,columnNames){
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
            }
        };
        
        jTable1.setModel(dtm);
        jTable1.setTableHeader(null);
        
        jTable1.updateUI();
                
        jPanelList.updateUI();
        this.updateUI();
        
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel jLabelName;
    private javax.swing.JPanel jPanelList;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
    
    public void setReadOnly( boolean b )
    {
        
        for (int i=0; i<jPanelList.getComponentCount(); ++i)
        {
            Component c = jPanelList.getComponent(i);
            if (c instanceof JCheckBox)
            {
               ((JCheckBox)c).setEnabled(!b);
            }
        }
    }

    public void addActionListener(ActionListener listener) {

        listeners.add(listener);
    }

}
