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


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.io.FileOutputStream;
import javax.swing.SwingUtilities;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.xml.JRXmlWriter;
import org.openide.cookies.OpenCookie;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.loaders.DataObject;
import org.openide.util.NbBundle;
/**
 *
 * @author gtoffoli
 */
public class ConvertJasperJrxmlDialog extends javax.swing.JDialog {


    private String jasperFile = null;
    private String jrxmlFile = null;

    /** Creates new form ConvertJasperJrxmlDialog */
    public ConvertJasperJrxmlDialog(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();
            }
        });

        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();
        jCheckBoxAtTheEnd = new javax.swing.JCheckBox();
        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();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

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

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

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

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

        jButtonBrowse.setText(org.openide.util.NbBundle.getMessage(ConvertJasperJrxmlDialog.class, "ConvertJasperJrxmlDialog.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/convert_jasper_jrxml.png"))); // NOI18N
        jLabel3.setText(org.openide.util.NbBundle.getMessage(ConvertJasperJrxmlDialog.class, "ConvertJasperJrxmlDialog.jLabel3.text")); // NOI18N

        jButtonCancel.setText(org.openide.util.NbBundle.getMessage(ConvertJasperJrxmlDialog.class, "ConvertJasperJrxmlDialog.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(ConvertJasperJrxmlDialog.class, "ConvertJasperJrxmlDialog.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(ConvertJasperJrxmlDialog.class, "ConvertJasperJrxmlDialog.jLabelError.text")); // NOI18N
        jLabelError.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);

        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(jCheckBoxAtTheEnd)
                    .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)))
                .addContainerGap())
            .add(jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 632, Short.MAX_VALUE)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap(480, 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(28, 28, 28)
                        .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))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(jCheckBoxAtTheEnd)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .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())
        );

        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;
                    }
            }

            JasperReport report = (JasperReport)JRLoader.loadObject(new File(jasperFile));
            JRXmlWriter.writeReport(report, new FileOutputStream(newFile), "UTF-8");

            if (jCheckBoxAtTheEnd.isSelected())
            {
                FileObject obj = FileUtil.toFileObject(newFile);
                final DataObject dataObj = DataObject.find(obj);
                if (dataObj != null && dataObj.getCookie(OpenCookie.class) != null)
                {
                    SwingUtilities.invokeLater(new Runnable() {

                        public void run() {
                            dataObj.getCookie(OpenCookie.class).open();
                        }
                    });
                }
            }
            else
            {
                SwingUtilities.invokeLater(new Runnable() {

                        public void run() {
                            JOptionPane.showMessageDialog(Misc.getMainFrame(), I18n.getString("ConvertJasperJrxmlDialog.fileConverted"),"", JOptionPane.INFORMATION_MESSAGE);
                        }
                    });
            }

        } catch (Throwable t)
        {
            jLabelError.setText("<html>" + I18n.getString("ConvertJasperJrxmlDialog.errorOnConversion", 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(".jrxml") || file.isDirectory()) ;
		    }
		    public String getDescription() {
			    return "JRXML *.jrxml";
		    }
	    });

	    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 jCheckBoxAtTheEnd;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabelError;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTextFieldDestination;
    // End of variables declaration//GEN-END:variables

    /**
     * @return the jasperFile
     */
    public String getJasperFile() {
        return jasperFile;
    }

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

    /**
     * @param jasperFile the jasperFile to set
     */
    public void setJasperFile(String jasperFile) {
        this.jasperFile = jasperFile;

        jrxmlFile = Misc.changeFileExtension(jasperFile, "jrxml");
        this.jTextFieldDestination.setText(jrxmlFile);

        checkFile();
    }

}
