/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ConvertJasperJrxmlDialog.java
 *
 * Created on 10-mar-2009, 19.50.20
 */

package com.jaspersoft.ireport.designer.jrctx;


import com.jaspersoft.ireport.designer.IReportManager;
import com.jaspersoft.ireport.designer.utils.Misc;
import java.io.File;
import javax.swing.JOptionPane;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import com.jaspersoft.ireport.locale.I18n;
import java.util.List;
import javax.swing.SwingUtilities;
import net.sf.jasperreports.chartthemes.simple.XmlChartThemeExtensionsRegistryFactory;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.util.NbBundle;
/**
 *
 * @author gtoffoli
 */
public class ExportToJarDialog extends javax.swing.JDialog {


    private JRCTXEditorSupport editorSupport = null;

    /** Creates new form ConvertJasperJrxmlDialog */
    public ExportToJarDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        jTextFieldDestination.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                checkFile();
            }

            public void removeUpdate(DocumentEvent e) {
                checkFile();
            }

            public void changedUpdate(DocumentEvent e) {
                checkFile();
            }
        });

        jTextFieldName.getDocument().addDocumentListener(new DocumentListener() {

            public void insertUpdate(DocumentEvent e) {
                checkFile();
            }

            public void removeUpdate(DocumentEvent e) {
                checkFile();
            }

            public void changedUpdate(DocumentEvent e) {
                checkFile();
            }
        });

        this.setLocationRelativeTo(null);
    }

    /** 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldDestination = new javax.swing.JTextField();
        jButtonBrowse = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jButtonCancel = new javax.swing.JButton();
        jButtonOk = new javax.swing.JButton();
        jLabelError = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldName = new javax.swing.JTextField();
        jCheckBox1 = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(org.openide.util.NbBundle.getMessage(ExportToJarDialog.class, "ExportToJarDialog.title")); // NOI18N

        jLabel1.setText(org.openide.util.NbBundle.getMessage(ExportToJarDialog.class, "ExportToJarDialog.jLabel1.text")); // NOI18N
        jLabel1.setVerticalAlignment(javax.swing.SwingConstants.TOP);

        jLabel2.setText(org.openide.util.NbBundle.getMessage(ExportToJarDialog.class, "ExportToJarDialog.jLabel2.text")); // NOI18N

        jTextFieldDestination.setText(org.openide.util.NbBundle.getMessage(ExportToJarDialog.class, "ExportToJarDialog.jTextFieldDestination.text")); // NOI18N

        jButtonBrowse.setText(org.openide.util.NbBundle.getMessage(ExportToJarDialog.class, "ExportToJarDialog.jButtonBrowse.text")); // NOI18N
        jButtonBrowse.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBrowseActionPerformed(evt);
            }
        });

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/ireport/designer/resources/export_jrctx.png"))); // NOI18N
        jLabel3.setText(org.openide.util.NbBundle.getMessage(ExportToJarDialog.class, "ExportToJarDialog.jLabel3.text")); // NOI18N

        jButtonCancel.setText(org.openide.util.NbBundle.getMessage(ExportToJarDialog.class, "ExportToJarDialog.jButtonCancel.text")); // NOI18N
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        jButtonOk.setText(org.openide.util.NbBundle.getMessage(ExportToJarDialog.class, "ExportToJarDialog.jButtonOk.text")); // NOI18N
        jButtonOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonOkActionPerformed(evt);
            }
        });

        jLabelError.setForeground(new java.awt.Color(204, 0, 0));
        jLabelError.setText(org.openide.util.NbBundle.getMessage(ExportToJarDialog.class, "ExportToJarDialog.jLabelError.text")); // NOI18N
        jLabelError.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);

        jLabel4.setText(org.openide.util.NbBundle.getMessage(ExportToJarDialog.class, "ExportToJarDialog.jLabel4.text")); // NOI18N

        jTextFieldName.setText(org.openide.util.NbBundle.getMessage(ExportToJarDialog.class, "ExportToJarDialog.jTextFieldName.text")); // NOI18N

        jCheckBox1.setSelected(true);
        jCheckBox1.setText(org.openide.util.NbBundle.getMessage(ExportToJarDialog.class, "ExportToJarDialog.jCheckBox1.text")); // NOI18N

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(jLabel3)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE)
                    .add(jLabelError, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE)
                    .add(jLabel4)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel2)
                            .add(jTextFieldDestination, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 327, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButtonBrowse))
                    .add(jTextFieldName, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE)
                    .add(jCheckBox1))
                .addContainerGap())
            .add(jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 632, Short.MAX_VALUE)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(486, Short.MAX_VALUE)
                .add(jButtonOk)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jButtonCancel)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jLabel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(3, 3, 3)
                        .add(jLabel4)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jTextFieldName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(jLabel2)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                            .add(jButtonBrowse)
                            .add(jTextFieldDestination, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                        .add(18, 18, 18)
                        .add(jCheckBox1)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jLabelError, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 39, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(jLabel3))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 10, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButtonCancel)
                    .add(jButtonOk))
                .addContainerGap())
        );

        getAccessibleContext().setAccessibleName(org.openide.util.NbBundle.getMessage(ExportToJarDialog.class, "ExportToJarDialog.AccessibleContext.accessibleName")); // NOI18N

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

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


        try {

            File newFile = new File(jTextFieldDestination.getText());
            if (newFile.exists())
            {
                if (JOptionPane.showConfirmDialog(Misc.getMainFrame(),
                            I18n.getString("LBL_File_Exists", newFile.getName()),
                            NbBundle.getMessage(DataObject.class, "CTL_SaveAsAction"),
                            JOptionPane.YES_NO_OPTION,
                            JOptionPane.WARNING_MESSAGE) != JOptionPane.OK_OPTION)
                    {
                        return;
                    }
            }

            XmlChartThemeExtensionsRegistryFactory.saveToJar(
                    editorSupport.getCurrentModel(), jTextFieldName.getText(),newFile);


            if (jCheckBox1.isSelected())
            {
                List<String> cp = IReportManager.getInstance().getRelodableClasspath();
                if (!cp.contains(""+newFile))
                {
                    cp.add(""+newFile);
                    IReportManager.getInstance().setRelodableClasspath(cp);
                }
            }

                SwingUtilities.invokeLater(new Runnable() {

                        public void run() {
                            JOptionPane.showMessageDialog(Misc.getMainFrame(), I18n.getString("ExportToJarDialog.fileExported"),"", JOptionPane.INFORMATION_MESSAGE);
                        }
                    });
        } catch (Throwable t)
        {
            jLabelError.setText("<html>" + I18n.getString("ExportToJarDialog.errorOnExport", t.getMessage()));
            t.printStackTrace();
            return;
        }

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

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

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

        javax.swing.JFileChooser jfc = new javax.swing.JFileChooser( IReportManager.getInstance().getCurrentDirectory());

	    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()) ;
		    }
		    public String getDescription() {
			    return "JAR *.jar";
		    }
	    });

	    jfc.setMultiSelectionEnabled(false);
	    jfc.setDialogType( javax.swing.JFileChooser.OPEN_DIALOG);
	    if  (jfc.showOpenDialog( this) == javax.swing.JOptionPane.OK_OPTION) {
		    java.io.File file = jfc.getSelectedFile();
                    try {
                        jTextFieldDestination.setText( file.getAbsolutePath() );
                    } catch (Exception ex){}
	    }

    }//GEN-LAST:event_jButtonBrowseActionPerformed



    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonBrowse;
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonOk;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabelError;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTextFieldDestination;
    private javax.swing.JTextField jTextFieldName;
    // End of variables declaration//GEN-END:variables

    public void checkFile()
    {
        jLabelError.setText("");
        jButtonOk.setEnabled(true);
//        File f = new File(this.jTextFieldDestination.getText());
        if (this.jTextFieldName.getText().length() == 0)
        {
            jLabelError.setText("Invalid theme name");
            jButtonOk.setEnabled(false);
            return;
        }
        
        if (this.jTextFieldDestination.getText().length() == 0)
        {
            jLabelError.setText("Invalid file name");
            jButtonOk.setEnabled(false);
            return;
        }
    }

    /**
     * @param jasperFile the jasperFile to set
     */
    public void setJRCTXEditorSupport(JRCTXEditorSupport editorSupport) {
        this.editorSupport = editorSupport;

        File f = FileUtil.toFile(editorSupport.getDataObject().getPrimaryFile());

        String s = Misc.changeFileExtension(f.getName(), "");
        if (s.endsWith(".")) s=s.substring(0,s.length()-1);
        this.jTextFieldName.setText(s);
        this.jTextFieldDestination.setText(Misc.changeFileExtension(f.getName(), "jar"));

        checkFile();
    }

}
