/*
 * 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;

import com.jaspersoft.ireport.designer.IReportManager;
import com.jaspersoft.ireport.designer.utils.Misc;
import com.jaspersoft.ireport.jasperserver.JServer;
import com.jaspersoft.ireport.jasperserver.JasperServerManager;
import com.jaspersoft.ireport.jasperserver.ui.actions.ICActionListener;
import com.jaspersoft.ireport.jasperserver.ui.inputcontrols.InputControlsUpdater;
import com.jaspersoft.ireport.jasperserver.ui.inputcontrols.BasicInputControl;
import com.jaspersoft.ireport.jasperserver.ui.inputcontrols.BooleanInputControl;
import com.jaspersoft.ireport.jasperserver.ui.inputcontrols.InputValidationException;
import com.jaspersoft.ireport.jasperserver.ui.inputcontrols.MultiColumnListInputControl;
import com.jaspersoft.ireport.jasperserver.ui.inputcontrols.MultiSelectInputControl;
import com.jaspersoft.ireport.jasperserver.ui.inputcontrols.SingleSelectInputControl;
import com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.ResourceDescriptor;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.List;
import javax.swing.JOptionPane;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import net.sf.jasperreports.engine.JRQueryChunk;
import net.sf.jasperreports.engine.design.JRDesignQuery;

/**
 *
 * @author  gtoffoli
 */
public class ReportUnitRunDialog extends javax.swing.JDialog {
    
    private int dialogResult = JOptionPane.CANCEL_OPTION;
    private java.util.HashMap parametersValues = null;
    private java.util.List inputControls = null;
    private JServer server = null;

    private Map<BasicInputControl, Thread> updaterThreads = new HashMap<BasicInputControl, Thread>();
    private String reportUnitUri = null;
    private org.jdesktop.swingx.JXBusyLabel busyLabel = new org.jdesktop.swingx.JXBusyLabel();

    private HashMap<String, Object> valuesCache = new HashMap<String, Object>();

    /**
     * This variable tracks which input controls (names) must be updated when a specific input control changes it's value.
     */
    private HashMap<String,List<String>> cascadingDependenciesMap = null;
    
    /** Creates new form NewReportUnitDialog */
    public ReportUnitRunDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        inputControls = new java.util.ArrayList();
        cascadingDependenciesMap = new HashMap<String,List<String>>();
        jScrollPane1.setViewportView( jPanelInputControls );
        
        setLocationRelativeTo(null);
        busyLabel.setBusy(false);
        jPanelStatus.add(busyLabel, BorderLayout.CENTER);
        busyLabel.setVisible(false);

        applyI18n();
    }
    
    public void applyI18n()
    {
        jButtonClose.setText( JasperServerManager.getString("reportUnitRunDialog.buttonCancel","Cancel"));
        jButtonSave.setText( JasperServerManager.getString("reportUnitRunDialog.buttonRunReport","Run report"));
        jLabel1.setText( JasperServerManager.getString("reportUnitRunDialog.title","Report parameters"));
    }


    
    /** 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;

        jPanelInputControls = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        jSeparator4 = new javax.swing.JSeparator();
        jPanel4 = new javax.swing.JPanel();
        jPanelStatus = new javax.swing.JPanel();
        jButtonSave = new javax.swing.JButton();
        jButtonClose = new javax.swing.JButton();

        jPanelInputControls.setMaximumSize(new java.awt.Dimension(450, 2147483647));
        jPanelInputControls.setMinimumSize(new java.awt.Dimension(50, 10));
        jPanelInputControls.setLayout(new java.awt.GridBagLayout());

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Report unit");
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setLayout(new java.awt.GridBagLayout());

        jLabel1.setFont(new java.awt.Font("Dialog", 1, 12));
        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/ireport/jasperserver/res/documents_label.png"))); // NOI18N
        jLabel1.setText("Report parameters");
        jLabel1.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jLabel1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        jPanel1.add(jLabel1, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        getContentPane().add(jPanel1, gridBagConstraints);

        jSeparator1.setMinimumSize(new java.awt.Dimension(2, 2));
        jSeparator1.setPreferredSize(new java.awt.Dimension(2, 2));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(jSeparator1, gridBagConstraints);

        jScrollPane1.setBorder(null);
        jScrollPane1.setMinimumSize(new java.awt.Dimension(421, 246));
        jScrollPane1.setPreferredSize(new java.awt.Dimension(421, 246));
        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(4, 4, 8, 4);
        getContentPane().add(jScrollPane1, gridBagConstraints);

        jSeparator4.setMinimumSize(new java.awt.Dimension(0, 2));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 6, 4);
        getContentPane().add(jSeparator4, gridBagConstraints);

        jPanel4.setMinimumSize(new java.awt.Dimension(10, 30));
        jPanel4.setPreferredSize(new java.awt.Dimension(10, 30));
        jPanel4.setLayout(new java.awt.GridBagLayout());

        jPanelStatus.setLayout(new java.awt.BorderLayout());
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 0);
        jPanel4.add(jPanelStatus, gridBagConstraints);

        jButtonSave.setText("Run report");
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
        jPanel4.add(jButtonSave, gridBagConstraints);

        jButtonClose.setText("Cancel");
        jButtonClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCloseActionPerformed(evt);
            }
        });
        jPanel4.add(jButtonClose, new java.awt.GridBagConstraints());

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(0, 4, 0, 4);
        getContentPane().add(jPanel4, gridBagConstraints);

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

    private void jButtonCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCloseActionPerformed

        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_jButtonCloseActionPerformed

    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
    
        java.util.HashMap newSuggestedValues = new java.util.HashMap();
        try {
            parametersValues = new java.util.HashMap();
            for (int i=0; i<inputControls.size(); ++i)
            {
                BasicInputControl ic = (BasicInputControl)inputControls.get(i);
                
                Object val = ic.validate();
                if (val != null)
                {
                    newSuggestedValues.put( ic.getInputControl().getName(), val);
                    if (val instanceof java.util.Date)
                    {
                        val = ""+ ((java.util.Date)val).getTime();
                        parametersValues.put( ic.getInputControl().getName(), ""+val);
                    }
                    else if (val instanceof java.util.Collection)
                    {
                        parametersValues.put( ic.getInputControl().getName(), val);
                    }
                    else
                    {
                        parametersValues.put( ic.getInputControl().getName(), ""+val);
                    }
                    
                }
                else
                {
                    if (ic.getInputControl().isMandatory())
                    {
                         throw new InputValidationException(
                                 JasperServerManager.getFormattedString("reportUnitRunDialog.message.mandatoryParameter","{0} is a mandatory parameter!",
                                    new Object[]{ic.getInputControl().getLabel()}));
                                 
                                 
                    }
                }
            }
        } catch (InputValidationException ex)
        {
            JOptionPane.showMessageDialog(Misc.getMainFrame(),ex.getMessage());
            ex.printStackTrace();
            return;
        }
        
        for (int i=0; i<newSuggestedValues.size(); ++i)
        {
               BasicInputControl ic = (BasicInputControl)inputControls.get(i);
               Object val = newSuggestedValues.get( ic.getInputControl().getName() );
               if (val != null)
               {
                   ic.addHistoryValue( ic.getInputControl().getUriString(), val );
               }
        }
        
        this.setDialogResult(JOptionPane.OK_OPTION);
        this.setVisible(false);
        this.dispose();    
    }//GEN-LAST:event_jButtonSaveActionPerformed
  
    public int getDialogResult() {
        return dialogResult;
    }

    public void setDialogResult(int dialogResult) {
        this.dialogResult = dialogResult;
    }

    /**
     * inputControlsDescriptors = a list of ibnput control descriptors
     */
    public void setInputControls(java.util.List inputControlsDescriptors)
    {
        setInputControls(inputControlsDescriptors, null);
    }
    
    /**
     * inputControlsDescriptors = a list of ibnput control descriptors
     */
    public void setInputControls(java.util.List inputControlsDescriptors, java.util.Map defaultValues)
    {
        if (inputControlsDescriptors == null) return;
        inputControls.clear();
        
        for (int i=0; i<inputControlsDescriptors.size(); ++i)
        {
            ResourceDescriptor rd = (ResourceDescriptor)inputControlsDescriptors.get(i);
            
            if (rd.getResourcePropertyValue(  ResourceDescriptor.PROP_INPUTCONTROL_IS_VISIBLE ) != null &&
                rd.getResourcePropertyValue(  ResourceDescriptor.PROP_INPUTCONTROL_IS_VISIBLE ).equals("false"))
            {
                continue;
            }

            Object defaultValue = null;
            if (defaultValues != null && defaultValues.containsKey(rd.getName()))
            {
                defaultValue = defaultValues.get(rd.getName());
            }    
             
            if (rd.getControlType() == rd.IC_TYPE_SINGLE_VALUE)
            {
                BasicInputControl bic = new BasicInputControl();
                
                ResourceDescriptor rdDataType = (ResourceDescriptor)rd.getChildren().get(0);
                
                if (rdDataType.getWsType().equals(ResourceDescriptor.TYPE_REFERENCE))
                {
                    ResourceDescriptor tmpRd = new ResourceDescriptor();
                       tmpRd.setUriString(rdDataType.getReferenceUri());
                    try {
                        rdDataType = this.getServer().getWSClient().get(tmpRd, null);
                    } catch (Exception ex)
                    {
                        JOptionPane.showMessageDialog(this,JasperServerManager.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}));
                        ex.printStackTrace();
                    }
                }
                bic.setInputControl(rd, rdDataType);
                
                
                
                if (defaultValue != null)
                {
                    Object formattedValue = defaultValue;
                    if (rdDataType != null && rdDataType.getDataType() == rdDataType.DT_TYPE_DATE)
                    {
                        java.util.Date date = new java.util.Date(Long.parseLong(""+defaultValue));
                        SimpleDateFormat format = new SimpleDateFormat(IReportManager.getInstance().getProperty("dateformat", "d/M/y"));
                        formattedValue = format.format(date);
                    }
                    else if (rdDataType != null && rdDataType.getDataType() == rdDataType.DT_TYPE_DATE_TIME)
                    {
                        java.util.Date date = new java.util.Date(Long.parseLong(""+defaultValue));
                        SimpleDateFormat format = new SimpleDateFormat(IReportManager.getInstance().getProperty("timeformat", "d/M/y H:m:s"));
                        formattedValue = format.format(date);
                    }
                    
                    bic.setDefaultValue(formattedValue);
                }
                inputControls.add(bic);
            }
            else if (rd.getControlType() == rd.IC_TYPE_BOOLEAN)
            {
                BooleanInputControl bic = new BooleanInputControl();
                bic.setInputControl(rd);
                if (defaultValue != null) bic.setDefaultValue(defaultValue);
                inputControls.add(bic);
            }
            else if (rd.getControlType() == rd.IC_TYPE_SINGLE_SELECT_LIST_OF_VALUES ||
                     rd.getControlType() == rd.IC_TYPE_SINGLE_SELECT_LIST_OF_VALUES_RADIO ||
                     rd.getControlType() == rd.IC_TYPE_MULTI_SELECT_LIST_OF_VALUES ||
                     rd.getControlType() ==  rd.IC_TYPE_MULTI_SELECT_LIST_OF_VALUES_CHECKBOX)
            {
                
                BasicInputControl bic = null;
                
                if (rd.getControlType() == rd.IC_TYPE_SINGLE_SELECT_LIST_OF_VALUES ||
                    rd.getControlType() == rd.IC_TYPE_SINGLE_SELECT_LIST_OF_VALUES_RADIO)
                {
                    bic = new SingleSelectInputControl();
                }
                else if (rd.getControlType() == rd.IC_TYPE_MULTI_SELECT_LIST_OF_VALUES ||
                         rd.getControlType() == rd.IC_TYPE_MULTI_SELECT_LIST_OF_VALUES_CHECKBOX)
                {
                    bic = new MultiSelectInputControl();
                }
                
                
                ResourceDescriptor rd2 = (ResourceDescriptor)rd.getChildren().get(0);
                List items = null;

                if (rd2.getWsType().equals(ResourceDescriptor.TYPE_REFERENCE))
                {
                    ResourceDescriptor tmpRd = new ResourceDescriptor();
                       tmpRd.setUriString(rd2.getReferenceUri());
                    try {
                        tmpRd = this.getServer().getWSClient().get(tmpRd, null);
                        items = tmpRd.getListOfValues();
                    } catch (Exception ex)
                    {
                        JOptionPane.showMessageDialog(this,JasperServerManager.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}));
                        ex.printStackTrace();
                    }
                }
                else
                {
                    items = ((ResourceDescriptor)rd.getChildren().get(0)).getListOfValues();
                }
                bic.setInputControl(rd, items);
                if (defaultValue != null) bic.setDefaultValue(defaultValue);
                inputControls.add(bic);
            }
            else if (rd.getControlType() == rd.IC_TYPE_SINGLE_SELECT_QUERY ||
                     rd.getControlType() == rd.IC_TYPE_SINGLE_SELECT_QUERY_RADIO ||
                     rd.getControlType() == rd.IC_TYPE_MULTI_SELECT_QUERY ||
                     rd.getControlType() ==  rd.IC_TYPE_MULTI_SELECT_QUERY_CHECKBOX)
            {
                
                BasicInputControl bic = null;
                
                if (rd.getControlType() == rd.IC_TYPE_SINGLE_SELECT_QUERY)
                {
                    bic = new MultiColumnListInputControl();
                }
                else if (rd.getControlType() == rd.IC_TYPE_SINGLE_SELECT_QUERY_RADIO)
                {
                    bic = new SingleSelectInputControl();
                }
                else if (rd.getControlType() == rd.IC_TYPE_MULTI_SELECT_QUERY ||
                         rd.getControlType() == rd.IC_TYPE_MULTI_SELECT_QUERY_CHECKBOX)
                {
                    bic = new MultiSelectInputControl();
                }
                
                ResourceDescriptor rd2 = (ResourceDescriptor)rd.getChildren().get(0);
                List items = null;

                bic.setInputControl(rd,rd.getQueryData());
                if (defaultValue != null) bic.setDefaultValue(defaultValue);
                inputControls.add(bic);
            }
        }
        
        int height = 0;
        for (int i=0; i<inputControls.size(); ++i)
        {
            BasicInputControl ic = (BasicInputControl)inputControls.get(i);

            // This is used for cascading input controls....
            ic.addActionListener(new ICActionListener(ic, this));
            cascadingDependencies(ic);


            java.awt.GridBagConstraints gridBagConstraints = new java.awt.GridBagConstraints();
            gridBagConstraints.gridx = 0;
            gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
            gridBagConstraints.weightx = 1.0;
            jPanelInputControls.add(ic.getUI(), gridBagConstraints);
            
            height += ic.getUI().getPreferredSize().height;
        }
        
        java.awt.GridBagConstraints gridBagConstraints2 = new java.awt.GridBagConstraints();
        gridBagConstraints2.gridx = 0;
        gridBagConstraints2.weighty = 1.0;
        gridBagConstraints2.weightx = 1.0;
        JPanel spacer = new JPanel();
        spacer.setPreferredSize(new java.awt.Dimension(1,1));
        jPanelInputControls.add(spacer, gridBagConstraints2);

        jPanelInputControls.setSize( 50, height);
            
        jPanelInputControls.doLayout();
        jPanelInputControls.updateUI();
        int panelHeight = jPanelInputControls.getPreferredSize().height;
        if (panelHeight > 0)
        {
            panelHeight = Math.min((int)(Misc.getMainFrame().getHeight()*0.8), panelHeight);
            jScrollPane1.setPreferredSize(new Dimension(jScrollPane1.getPreferredSize().width, panelHeight));
        }
        pack();
        setLocationRelativeTo(null);

        Thread t = new Thread(new Runnable() {

            public void run() {
                for (int i=0; i<inputControls.size(); ++i)
                {
                    BasicInputControl ic = (BasicInputControl)inputControls.get(i);
                    actionPerformed(ic);
                }
            }
        });

        t.start();
        
        
        
    }
    
    public java.util.Map getParametersValues()
    {
        return parametersValues;
    }

    public JServer getServer() {
        return server;
    }

    public void setServer(JServer server) {
        this.server = server;
    }
 
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonClose;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanelInputControls;
    private javax.swing.JPanel jPanelStatus;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator4;
    // End of variables declaration//GEN-END:variables

    public void actionPerformed(BasicInputControl ic) {

        try {
            //jLabel2.setText(ic.getInputControl().getName() + "=" + ic.getValue());

            String updateICName = ic.getInputControl().getName();
            
            // get the first input control having this param in the list...

            for (int k=0; k<inputControls.size(); ++k)
            {
                BasicInputControl icToUpdate = (BasicInputControl)inputControls.get(k);
                if (icToUpdate == null || icToUpdate == ic) continue;

                String icName = icToUpdate.getInputControl().getName();

                 if ( cascadingDependenciesMap.get(icName) == null ||
                      !cascadingDependenciesMap.get(icName).contains(updateICName))
                 {
                     continue;
                 }

                HashMap parameters = new HashMap();
                List<String> parametersICs = cascadingDependenciesMap.get(icName);
                for (String paramName : parametersICs)
                {

                    try {
                        Object value = getInputControlValue(paramName);
                        parameters.put(paramName, value);
                    } catch (InputValidationException ex)
                    {
                        JOptionPane.showMessageDialog(Misc.getMainFrame(),ex.getMessage());
                        ex.printStackTrace();
                        return;
                    }
                }
                
                Thread updaterThread = updaterThreads.get(icToUpdate);

                if (updaterThread != null)
                {
                    updaterThread.interrupt();
                }

                System.out.println("Updating input control: " + icToUpdate.getInputControl().getName());
                System.out.flush();
                updaterThread = new Thread(new InputControlsUpdater(this.getServer(), icToUpdate, getReportUnitUri(), parameters, this));
                updaterThreads.put(icToUpdate, updaterThread);
                updaterThread.start();
            }


        } catch (Exception ex) {
            
        }
    }

    /**
     * Keep track of input parameters required to update this input control...
     * @param ic
     */
    private void cascadingDependencies(BasicInputControl bic) {

        ResourceDescriptor ic = bic.getInputControl();

        if (ic.getControlType() == ResourceDescriptor.IC_TYPE_SINGLE_SELECT_QUERY ||
            ic.getControlType() == ResourceDescriptor.IC_TYPE_SINGLE_SELECT_QUERY_RADIO ||
            ic.getControlType() == ResourceDescriptor.IC_TYPE_MULTI_SELECT_QUERY ||
            ic.getControlType() == ResourceDescriptor.IC_TYPE_MULTI_SELECT_QUERY_CHECKBOX)
        {
            // Look if this query has a specific datasource...
            for (int k=0; k<ic.getChildren().size(); ++k)
            {
                ResourceDescriptor sub_ic = (ResourceDescriptor)ic.getChildren().get(k);
                if (sub_ic.getWsType().equals(ResourceDescriptor.TYPE_QUERY) )
                {
                    String queryString = sub_ic.getResourceProperty(ResourceDescriptor.PROP_QUERY).getValue();
                    String lang = sub_ic.getResourceProperty(ResourceDescriptor.PROP_QUERY_LANGUAGE).getValue();
                    // Check for parameters...
                    List<String> parameters = new ArrayList<String>();



                    if (queryString != null && queryString.length() > 0)
                    {
                        JRDesignQuery query = new JRDesignQuery();
                        query.setText(queryString);
                        if (lang != null) query.setLanguage(lang);
                        JRQueryChunk[] chunks = query.getChunks();
                        
                        for (int i=0; i<chunks.length; ++i)
                        {
                            switch (chunks[i].getType())
                            {
                                case JRQueryChunk.TYPE_TEXT:
                                    break;
                                case JRQueryChunk.TYPE_PARAMETER_CLAUSE:
                                {
                                    // adding a parameter...
                                    String paramName = chunks[i].getText();
                                    if(!parameters.contains(paramName) )
                                    {
                                        parameters.add(paramName);
                                    }
                                    break;
                                }
                                case JRQueryChunk.TYPE_PARAMETER:
                                {
                                    // adding a parameter...
                                    String paramName = chunks[i].getText();
                                    if(!parameters.contains(paramName) )
                                    {
                                        parameters.add(paramName);
                                    }
                                    break;
                                }
                                case JRQueryChunk.TYPE_CLAUSE_TOKENS:
                                {
                                    String[] tokens = chunks[i].getTokens();
                                    if (tokens.length > 2)
                                    {
                                        for (int t=2; t<tokens.length; ++t)
                                        {
                                            if(!parameters.contains(tokens[t].trim()) )
                                            {
                                                parameters.add(tokens[t].trim());
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                        }
                    }
                    
                    if (parameters.size() > 0)
                    {
                        cascadingDependenciesMap.put(ic.getName(), parameters);
                    }

                    break;
                }
            }
        }

    }

    public Object getInputControlValue(String paramName) throws InputValidationException
    {
        for (int i=0; i<inputControls.size(); ++i)
        {
                BasicInputControl ic = (BasicInputControl)inputControls.get(i);
                if (ic.getInputControl().getName().equals(paramName))
                {

                    Object val = ic.validate();
                    if (val != null)
                    {
                        if (val instanceof java.util.Date)
                        {
                            return ""+ ((java.util.Date)val).getTime();
                        }
                        else if (val instanceof java.util.Collection)
                        {
                            return val;
                        }
                        else
                        {
                            return ""+val;
                        }
                    }

                    return val;
                }
        }
        return null;
    }

    /**
     * @return the reportUnitUri
     */
    public String getReportUnitUri() {
        return reportUnitUri;
    }

    /**
     * @param reportUnitUri the reportUnitUri to set
     */
    public void setReportUnitUri(String reportUnitUri) {
        this.reportUnitUri = reportUnitUri;
    }

    public void setBusy(boolean b)
    {
        busyLabel.setVisible(b);
        busyLabel.setBusy(b);
    }

    /**
     * @return the valuesCache
     */
    public HashMap<String, Object> getValuesCache() {
        return valuesCache;
    }

    /**
     * @param valuesCache the valuesCache to set
     */
    public void setValuesCache(HashMap<String, Object> valuesCache) {
        this.valuesCache = valuesCache;
    }

}
