/*
 * Copyright (C) 2005 - 2006 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 free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as published by
 * the Free Software Foundation.
 *
 * This program is distributed WITHOUT ANY WARRANTY; and without the
 * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see http://www.gnu.org/licenses/gpl.txt
 * or write to:
 *
 * Free Software Foundation, Inc.,
 * 59 Temple Place - Suite 330,
 * Boston, MA  USA  02111-1307
 *
 *
 *
 *
 * UserTemplatesDialog.java
 *
 * Created on 22 aprile 2005, 18.05
 *
 */

package it.businesslogic.ireport.gui.wizard;

import it.businesslogic.ireport.Report;
import it.businesslogic.ireport.gui.*;
import it.businesslogic.ireport.util.I18nOptionPane;
import it.businesslogic.ireport.util.Misc;
import it.businesslogic.ireport.util.ReportGenerator;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.DefaultListModel;
import java.util.*;
import javax.swing.JCheckBox;
import it.businesslogic.ireport.util.I18n;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/**
 *
 * @author  Administrator
 */
public class UserTemplatesDialog extends javax.swing.JDialog {

    private int dialogResult = javax.swing.JOptionPane.CANCEL_OPTION;
    private boolean modifiedList = false;
    /** Creates new form ClassPathDialog */
    public UserTemplatesDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        applyI18n();    
        jList1.setModel(new DefaultListModel());
        it.businesslogic.ireport.util.Misc.centerFrame( this );


        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, "ESCAPE");
        getRootPane().getActionMap().put("ESCAPE", escapeAction);

        
        DefaultListModel dlm = new DefaultListModel();
        jList1.setModel(dlm);

         
         java.util.List list = MainFrame.getMainInstance().getUserChoicesWizardTemplates();
         
         for (int i=0; i<list.size(); ++i)
         {
             dlm.addElement( list.get(i) );
         }
        
         if (list.size() > 0)
         {
             jList1.setSelectedIndex(0);
         }
         
        jList1.updateUI();
         
        //to make the default button ...
        this.getRootPane().setDefaultButton(this.jButtonSave);
    }

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

        jScrollPane2 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jPanel1 = new javax.swing.JPanel();
        jButtonCreateReports = new javax.swing.JButton();
        jButtonDeleteTemplate = new javax.swing.JButton();
        jButtonSave = new javax.swing.JButton();
        jButtonCancel = new javax.swing.JButton();

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

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Classpath");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jScrollPane2.setPreferredSize(new java.awt.Dimension(258, 300));
        jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                jList1ValueChanged(evt);
            }
        });

        jScrollPane2.setViewportView(jList1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        getContentPane().add(jScrollPane2, gridBagConstraints);

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

        jPanel1.setMinimumSize(new java.awt.Dimension(120, 10));
        jPanel1.setPreferredSize(new java.awt.Dimension(120, 10));
        jButtonCreateReports.setText("Create report(s)");
        jButtonCreateReports.setToolTipText("Create report from selected template");
        jButtonCreateReports.setEnabled(false);
        jButtonCreateReports.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDeselectAllActionPerformed1(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0);
        jPanel1.add(jButtonCreateReports, gridBagConstraints);

        jButtonDeleteTemplate.setText("Delete temlplate");
        jButtonDeleteTemplate.setToolTipText("");
        jButtonDeleteTemplate.setEnabled(false);
        jButtonDeleteTemplate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCreateReportsjButtonDeselectAllActionPerformed1(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0);
        jPanel1.add(jButtonDeleteTemplate, gridBagConstraints);

        jButtonSave.setText("Save");
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 4, 0);
        jPanel1.add(jButtonSave, gridBagConstraints);

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

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

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        getContentPane().add(jPanel1, gridBagConstraints);

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

    private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged

        if (jList1.getSelectedIndex() >=0)
        {
            jButtonCreateReports.setEnabled(true);
            jButtonDeleteTemplate.setEnabled(true);
        }
        else
        {
            jButtonCreateReports.setEnabled(false);
            jButtonDeleteTemplate.setEnabled(false);
        }
        
    }//GEN-LAST:event_jList1ValueChanged

    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
        
        
        List list = MainFrame.getMainInstance().getUserChoicesWizardTemplates();
        list.clear();
        DefaultListModel dlm = (DefaultListModel)jList1.getModel();
        for (int i=0; i<dlm.getSize(); ++i)
        {
            list.add(dlm.getElementAt(i));
        }
        
        UserChoicesWizardTemplate.storeWizardTemplates(list);
        
        setDialogResult(javax.swing.JOptionPane.OK_OPTION);
        setVisible(false);
    }//GEN-LAST:event_jButtonSaveActionPerformed

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

        DefaultListModel dlm = (DefaultListModel)jList1.getModel();
        int[] indexes = jList1.getSelectedIndices();
        for (int i = indexes.length-1; i>=0; --i)
        {
            dlm.remove(indexes[i]);
            modifiedList = true;
        }
        
    }//GEN-LAST:event_jButtonCreateReportsjButtonDeselectAllActionPerformed1

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

        
        Object[] templates = jList1.getSelectedValues();
        if (templates.length == 0) return;
        
        
        int filesCreated = 0;
        
        // Ask for destination directory...
        
        javax.swing.JFileChooser jfc = new javax.swing.JFileChooser( MainFrame.getMainInstance().getCurrentDirectory());

        jfc.setDialogTitle("Select output directory");
        jfc.setDialogTitle(it.businesslogic.ireport.util.I18n.getString("selectOutputDirectory", "Select output directory"));//I18N

        jfc.setAcceptAllFileFilterUsed(true);
        jfc.setFileSelectionMode( jfc.DIRECTORIES_ONLY );
        /*jfc.addChoosableFileFilter( new javax.swing.filechooser.FileFilter() {
            public boolean accept(java.io.File file) {
                String filename = file.getName();
                return (filename.toLowerCase().endsWith(".jar") || file.isDirectory() ||
                        filename.toLowerCase().endsWith(".zip")
                        ) ;
            }
            public String getDescription() {
                return "*.jar, *.zip";
            }
        });
         */

        jfc.setMultiSelectionEnabled(false);

        jfc.setDialogType( javax.swing.JFileChooser.OPEN_DIALOG);
        if  (jfc.showOpenDialog( this) == javax.swing.JOptionPane.OK_OPTION) {
            java.io.File directory = jfc.getSelectedFile();

            MainFrame.getMainInstance().setCurrentDirectory(directory, true);
            
            for (int i = templates.length-1; i>=0; --i)
            {
                UserChoicesWizardTemplate template = (UserChoicesWizardTemplate)templates[i];
                File file = new File(directory, Misc.string_replace("_"," ", template.getName() ) + ".jrxml");
                
                if (file.exists())
                {
                    //is different file to save?
                    //confirm overwrite
                   int ret = JOptionPane.showConfirmDialog(this, 
                            I18n.getFormattedString("userTemplatesDialog.message.overwrite","The file {0} already exists.\nDo you want overwrite it?",new Object[]{""+file}),
                                    "",  JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);
                    
                            
                    if (ret == JOptionPane.CANCEL_OPTION) break;
                    if (ret == JOptionPane.NO_OPTION)
                    {
                        // Select a new File...
                        jfc = new javax.swing.JFileChooser(MainFrame.getMainInstance().getCurrentDirectory());
                        jfc.setDialogTitle("Save report as XML jasperreports file...");

                        // Handling the new File, that gets saved for the first time
                        // Propose a new file name based on the report name

                        jfc.setSelectedFile( file ) ;

                        jfc.setFileFilter( new javax.swing.filechooser.FileFilter()
                        {
                            public boolean accept(java.io.File file)
                            {
                                String filename = file.getName();
                                return (filename.toLowerCase().endsWith(".xml") || file.isDirectory() || filename.toLowerCase().endsWith(".jrxml")) ;
                            }
                            public String getDescription()
                            {
                                return "JasperReports XML *.xml, *.jrxml";
                            }
                        });
                        jfc.setMultiSelectionEnabled(false);
                        jfc.setDialogType( javax.swing.JFileChooser.SAVE_DIALOG);

                        // Show the dialog:
                        if  (jfc.showSaveDialog(this) != javax.swing.JOptionPane.OK_OPTION)
                        {
                            return;
                        }

                        file = jfc.getSelectedFile();
                    }
                }
                
                try {
                    Report report = ReportGenerator.createReport(template);
                    report.saveXMLFile( ""+file );
                    filesCreated++;
                } catch (Exception ex)
                {
                   JOptionPane.showMessageDialog(this,ex.getMessage(), I18n.getString("message.title.exception","Exception"), JOptionPane.ERROR_MESSAGE);
                   break;
                }
            }
            
            JOptionPane.showMessageDialog(this,I18n.getFormattedString("userTemplatesDialog.message.createdReports","{0} report(s) created successful.", new Object[]{new Integer(filesCreated)}), "",JOptionPane.INFORMATION_MESSAGE);
        }
        
        
        
        
    }//GEN-LAST:event_jButtonDeselectAllActionPerformed1

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed

    }//GEN-LAST:event_formWindowClosed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing

        // Save all...
        if (modifiedList)
        {
            int ret = javax.swing.JOptionPane.showConfirmDialog(this, it.businesslogic.ireport.util.I18n.getString("userTemplatesDialog.saveTemplatesList", "Do you want save the changes ?"));

            if (ret == javax.swing.JOptionPane.CANCEL_OPTION)
            {
                return;
            }

            jButtonSaveActionPerformed(null);
        }
        else
        {
            setVisible(false);
        }
    }//GEN-LAST:event_formWindowClosing

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
        setVisible(false);
    }//GEN-LAST:event_jButtonCancelActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ClassPathDialog(new javax.swing.JFrame(), true).setVisible(true);
            }
        });
    }

   



    public int getDialogResult() {
        return 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 jButtonCreateReports;
    private javax.swing.JButton jButtonDeleteTemplate;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JList jList1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    // End of variables declaration//GEN-END:variables

    public void applyI18n(){
                // Start autogenerated code ----------------------
        jButtonCancel.setText(I18n.getString("jRFieldDialog.buttonCancel","Cancel"));
        jButtonCreateReports.setText(I18n.getString("userTemplatesDialog.buttonGenerateReport","Generate report(s)"));
        jButtonDeleteTemplate.setText(I18n.getString("userTemplatesDialog.buttonRemoveTemplate","Remove template"));
        jButtonSave.setText(I18n.getString("userTemplatesDialog.buttonSave","Save changes"));
        
        this.setTitle(I18n.getString("userTemplatesDialog.title","User choices templates"));
                        // End autogenerated code ----------------------
    }
}
