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

import com.jaspersoft.ireport.designer.editor.ExpObjectCellRenderer;
import com.jaspersoft.ireport.designer.sheet.Tag;
import com.jaspersoft.ireport.locale.I18n;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import net.sf.jasperreports.engine.design.JRDesignDataset;
import net.sf.jasperreports.engine.design.JRDesignField;
import net.sf.jasperreports.engine.design.JRDesignSortField;
import net.sf.jasperreports.engine.design.JRDesignVariable;
import net.sf.jasperreports.engine.type.SortFieldTypeEnum;
import net.sf.jasperreports.engine.type.SortOrderEnum;
/**
 *
 * @author  Administrator
 */
public class SortFieldDialog extends javax.swing.JDialog {
    /**
     * Creates new form SortFieldDialog
     */
    private JRDesignSortField tmpSortField = null;
    
    public SortFieldDialog(java.awt.Dialog parent, boolean modal) {
        
        super(parent, modal);
        initComponents();
        jComboBoxSortBy.setEditable(false);

        jComboBoxSortType.addItem(new Tag(SortOrderEnum.ASCENDING,"Ascending"));
        jComboBoxSortType.addItem(new Tag(SortOrderEnum.DESCENDING,"Descending"));

        ExpObjectCellRenderer renderer = new ExpObjectCellRenderer();
        renderer.setShowObjectType(true);
        renderer.setShowObjectClass(false);
        jComboBoxSortBy.setRenderer(renderer);
        
        javax.swing.KeyStroke escape =  javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_ESCAPE, 0, false);
        javax.swing.Action escapeAction = new javax.swing.AbstractAction() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                jButtonCancelActionPerformed(e);
            }
        };
       
        getRootPane().getInputMap(javax.swing.JComponent.WHEN_IN_FOCUSED_WINDOW).put(escape, I18n.getString("Global.Pane.Escape"));
        getRootPane().getActionMap().put(I18n.getString("Global.Pane.Escape"), escapeAction);


        //to make the default button ...
        this.getRootPane().setDefaultButton(this.jButtonOK);
        
        //applyI18n();
        this.pack();
        
    }
    
    /*
    public void applyI18n()
    {
                // Start autogenerated code ----------------------
                // End autogenerated code ----------------------
        this.setTitle( I18n.getString("sortFieldDialog.title","Sort field") );
        jLabelSortBy.setText( I18n.getString("sortFieldDialog.labelSortBy","Sort by..."));
        jLabelSortType.setText( I18n.getString("sortFieldDialog.labelSortType","Sort type"));
        this.jComboBoxSortType.removeAllItems();
        this.jComboBoxSortType.addItem(new Tag("Ascending",I18n.getString("sortFieldDialog.Ascending","Ascending")));
        this.jComboBoxSortType.addItem(new Tag("Descending",I18n.getString("sortFieldDialog.Descending","Descending")));
        Misc.setComboboxSelectedTagValue(jComboBoxSortType, "Ascending");
        jButtonOK.setText( I18n.getString("ok","Ok"));
        jButtonCancel.setText(I18n.getString("cancel","Cancel"));
    }
    */
    
    /**
     * Populate the fields combobox
     */
    @SuppressWarnings("unchecked")
    public void setDataset(JRDesignDataset ds)
    {
        jComboBoxSortBy.removeAllItems();
        List newList = new ArrayList();
        newList.addAll(ds.getFieldsList());
        newList.addAll(ds.getVariablesList());

        Object[] objs = newList.toArray();

        Arrays.sort(objs, new Comparator() {

            public int compare(Object o1, Object o2) {

                String name1 = null;
                String name2 = null;
                if (o1 instanceof JRDesignField && o2 instanceof JRDesignVariable)
                {
                   return 1;
                }
                else if (o2 instanceof JRDesignField && o1 instanceof JRDesignVariable)
                {
                    return -1;
                }

                if (o1 instanceof JRDesignField)
                {
                    name1 = ((JRDesignField)o1).getName();
                }
                else if (o1 instanceof JRDesignVariable)
                {
                    name1 = ((JRDesignVariable)o1).getName();
                }
                if (o2 instanceof JRDesignField)
                {
                    name2 = ((JRDesignField)o1).getName();
                }
                if (o2 instanceof JRDesignVariable)
                {
                    name2 = ((JRDesignVariable)o1).getName();
                }

                if (name1 == null || name2 == null) return 0;

                return name1.compareToIgnoreCase(name2);
            }
        });

        jComboBoxSortBy.setModel(new DefaultComboBoxModel( objs ) );
    }
    
    /** 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;

        jLabelSortBy = new javax.swing.JLabel();
        jComboBoxSortBy = new javax.swing.JComboBox();
        jSeparator1 = new javax.swing.JSeparator();
        jPanel1 = new javax.swing.JPanel();
        jButtonOK = new javax.swing.JButton();
        jButtonCancel = new javax.swing.JButton();
        jLabelSortType = new javax.swing.JLabel();
        jComboBoxSortType = new javax.swing.JComboBox();

        setTitle("Add/modify parameter");
        setModal(true);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jLabelSortBy.setText("Sort by");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 4);
        getContentPane().add(jLabelSortBy, gridBagConstraints);

        jComboBoxSortBy.setPreferredSize(new java.awt.Dimension(250, 22));
        jComboBoxSortBy.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxSortByActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        getContentPane().add(jComboBoxSortBy, 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.gridy = 8;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
        gridBagConstraints.weighty = 1.0;
        getContentPane().add(jSeparator1, gridBagConstraints);

        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        jButtonOK.setMnemonic('o');
        jButtonOK.setText("OK");
        jButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonOKActionPerformed(evt);
            }
        });
        jPanel1.add(jButtonOK);

        jButtonCancel.setMnemonic('c');
        jButtonCancel.setText("Cancel");
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });
        jPanel1.add(jButtonCancel);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 9;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(jPanel1, gridBagConstraints);

        jLabelSortType.setText("Sort type");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 4;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 0, 4);
        getContentPane().add(jLabelSortType, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 5;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 8, 4);
        getContentPane().add(jComboBoxSortType, gridBagConstraints);

        pack();
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Dimension dialogSize = getSize();
        setLocation((screenSize.width-dialogSize.width)/2,(screenSize.height-dialogSize.height)/2);
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
        setVisible(false);
        this.setDialogResult( javax.swing.JOptionPane.CANCEL_OPTION);
        dispose();
    }//GEN-LAST:event_jButtonCancelActionPerformed

    private void jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOKActionPerformed
        
        Object obj = this.jComboBoxSortBy.getSelectedItem();
        
        if (obj == null)
        {
            javax.swing.JOptionPane.showMessageDialog(this,
                    //I18n.getString("sortFieldDialog.messageNotValidField",
                    I18n.getString("SortFieldDialog.Message.Error"),
                    //I18n.getString("sortFieldDialog.messageTitleNotValidField",
                    I18n.getString("SortFieldDialog.Message.Error2"),
                    javax.swing.JOptionPane.WARNING_MESSAGE );
            return;
        }

        String fieldName = "";
        tmpSortField = new JRDesignSortField();

        if (obj instanceof JRDesignField)
        {
            fieldName = ((JRDesignField)obj).getName();
            tmpSortField.setType(SortFieldTypeEnum.FIELD);
        }
        else if (obj instanceof JRDesignVariable)
        {
            fieldName = ((JRDesignVariable)obj).getName();
            tmpSortField.setType(SortFieldTypeEnum.VARIABLE);
        }
        
        
        tmpSortField.setName(fieldName);
        tmpSortField.setOrder( (jComboBoxSortType.getSelectedIndex() == 1) ? 
                    SortOrderEnum.DESCENDING : SortOrderEnum.ASCENDING);

        setVisible(false);
        this.setDialogResult( javax.swing.JOptionPane.OK_OPTION);
        dispose();
    }//GEN-LAST:event_jButtonOKActionPerformed
    
    /** Closes the dialog */
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
        setVisible(false);
        this.setDialogResult( javax.swing.JOptionPane.CLOSED_OPTION);
        dispose();
    }//GEN-LAST:event_closeDialog

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




    }//GEN-LAST:event_jComboBoxSortByActionPerformed
    
    
    /** Getter for property dialogResult.
     * @return Value of property dialogResult.
     *
     */
    public int getDialogResult() {
        return dialogResult;
    }
    
    /** Setter for property dialogResult.
     * @param dialogResult New value of property dialogResult.
     *
     */
    public void setDialogResult(int dialogResult) {
        this.dialogResult = dialogResult;
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonOK;
    private javax.swing.JComboBox jComboBoxSortBy;
    private javax.swing.JComboBox jComboBoxSortType;
    private javax.swing.JLabel jLabelSortBy;
    private javax.swing.JLabel jLabelSortType;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    // End of variables declaration//GEN-END:variables

    private int dialogResult;    

    /**
     * return a new sortField instance
     */
    public JRDesignSortField getSortField() {
        return tmpSortField;
    }

    public void setSortField(JRDesignSortField sortField) {
        this.tmpSortField = new JRDesignSortField();
        this.tmpSortField.setName(  sortField.getName() );
        this.tmpSortField.setOrder(  sortField.getOrderValue() );
        this.tmpSortField.setType( sortField.getType() );
        this.tmpSortField.setName( sortField.getName());

        for (int i=0; i<jComboBoxSortBy.getItemCount(); ++i)
        {
            Object item = jComboBoxSortBy.getItemAt(i);

            if (item instanceof JRDesignField &&
                sortField.getType() == SortFieldTypeEnum.FIELD &&
                ((JRDesignField)item).getName().equals(sortField.getName()))
            {
                jComboBoxSortBy.setSelectedIndex(i);
                break;
            }
            else if (item instanceof JRDesignVariable &&
                sortField.getType() == SortFieldTypeEnum.VARIABLE &&
                ((JRDesignVariable)item).getName().equals(sortField.getName()))
            {
                jComboBoxSortBy.setSelectedIndex(i);
                break;
            }
        }

        this.jComboBoxSortType.setSelectedIndex( ((tmpSortField.getOrderValue() == SortOrderEnum.DESCENDING) ? 1 : 0) );
    }
    
}
