/*
 * 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.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.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.InputControlQueryDataRow;
import com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.ListItem;
import com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.ResourceDescriptor;
import java.util.List;
import javax.swing.JOptionPane;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import javax.swing.JPanel;

/**
 *
 * @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;
    
    /** Creates new form NewReportUnitDialog */
    public ReportUnitRunDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        inputControls = new java.util.ArrayList();
        jScrollPane1.setViewportView( jPanelInputControls );
        
        setLocationRelativeTo(null);
        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();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jSeparator4 = new javax.swing.JSeparator();
        jPanel4 = 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);

        jPanel2.setPreferredSize(new java.awt.Dimension(400, 185));
        jPanel2.setLayout(new java.awt.GridBagLayout());

        jScrollPane1.setBorder(null);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        jPanel2.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);
        jPanel2.add(jSeparator4, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        getContentPane().add(jPanel2, gridBagConstraints);

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

        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);
            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)
                    {
                        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);
            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();
    }
    
    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 jPanel2;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanelInputControls;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator4;
    // End of variables declaration//GEN-END:variables
}
