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

import com.jaspersoft.ireport.locale.I18n;
import java.io.IOException;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import nickyb.sqleonardo.environment.Application;
import nickyb.sqleonardo.querybuilder.QueryActions;
import nickyb.sqleonardo.querybuilder.QueryModel;
import nickyb.sqleonardo.querybuilder.syntax.SQLParser;



/**
 *
 * @author  gtoffoli
 */
public class QueryBuilderDialog extends javax.swing.JDialog {
    
    private String query = null;
    private int dialogResult = javax.swing.JOptionPane.CANCEL_OPTION;
    private boolean init = false;
    
    /**
     * Creates new form QueryBuilderDialog
     */
    public QueryBuilderDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initAll();
    }
    
    /**
     * Creates new form QueryBuilderDialog
     */
    public QueryBuilderDialog(java.awt.Dialog parent, boolean modal) {
        super(parent, modal);
        initAll();
    }
    
    public void applyI18n()
    {
        
        jTabbedPane1.setTitleAt(0, //I18n.getString("application.builder",
                I18n.getString("QueryBuilderDialog.Pane.Builder"));
        jTabbedPane1.setTitleAt(1, //I18n.getString("application.syntax",
                I18n.getString("QueryBuilderDialog.Title.SQL"));
        
        jButtonOk.setText( I18n.getString("Global.Button.Ok") );
        jButtonCancel.setText( I18n.getString("Global.Button.Cancel"));
        
    }
    
    private void initAll()
    {
        setInit(true);
        initComponents();
        applyI18n();
        setInit(false);
        setLocationRelativeTo(null);
    }
    
    public void setConnection(java.sql.Connection c)
    {
        this.queryBuilder1.setConnection(c);
    }
    
    /** 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;

        jTabbedPane1 = new javax.swing.JTabbedPane();
        queryBuilder1 = new nickyb.sqleonardo.querybuilder.QueryBuilder();
        jEditorPaneSQL = new javax.swing.JEditorPane();
        jPanel1 = new javax.swing.JPanel();
        jButtonOk = new javax.swing.JButton();
        jButtonCancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jTabbedPane1.setTabPlacement(javax.swing.JTabbedPane.BOTTOM);
        jTabbedPane1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jTabbedPane1StateChanged(evt);
            }
        });

        queryBuilder1.setPreferredSize(new java.awt.Dimension(600, 483));
        jTabbedPane1.addTab(I18n.getString("QueryBuilderDialog.Pane.Design"), queryBuilder1); // NOI18N

        jEditorPaneSQL.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jEditorPaneSQL.setMinimumSize(new java.awt.Dimension(50, 200));
        jEditorPaneSQL.setPreferredSize(new java.awt.Dimension(661, 340));
        jTabbedPane1.addTab(I18n.getString("QueryBuilderDialog.Pane.SQL"), jEditorPaneSQL); // NOI18N

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

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

        jButtonOk.setText(I18n.getString("Global.Button.Ok")); // NOI18N
        jButtonOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonOkActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 0);
        jPanel1.add(jButtonOk, gridBagConstraints);

        jButtonCancel.setText(I18n.getString("Global.Button.Cancel")); // NOI18N
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        jPanel1.add(jButtonCancel, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        getContentPane().add(jPanel1, gridBagConstraints);

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

    private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabbedPane1StateChanged

            if (isInit()) return; 
            if(jTabbedPane1.getSelectedIndex() == 0)
		{
			String msql = queryBuilder1.getModel().toString(true);
			String tsql = jEditorPaneSQL.getText();
			
			if(!tsql.equals(msql))
			{
				if(JOptionPane.showConfirmDialog( this, //I18n.getString("application.syntaxChanged",
                                        I18n.getString("QueryBuilderDialog.Message.Confirm")) == JOptionPane.OK_OPTION)
				{
					// this thread resolve: IllegalComponentStateException
					new Thread(new Runnable()
					{
						public void run()
						{
							while(!queryBuilder1.isVisible());
							try
							{
								QueryModel qm = SQLParser.toQueryModel(jEditorPaneSQL.getText());
								queryBuilder1.setModel(qm);
							}
							catch (IOException e)
							{
								JOptionPane.showMessageDialog(QueryBuilderDialog.this,// I18n.getString("errorParsingSQL",
                                                                        I18n.getString("QueryBuilderDialog.Message.Warning"));
                                                                jTabbedPane1.setSelectedIndex(0);
                                                        }
						}
					}).start();
				}
			}
		}
		else
                {
                    try {
		
                        jEditorPaneSQL.setText(queryBuilder1.getModel().toString(true));
                    
                    } catch (Exception ex)
                    {
                        
                    }
                }
        
    }//GEN-LAST:event_jTabbedPane1StateChanged

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

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

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

        if (jTabbedPane1.getSelectedIndex() == 0)
        {
            query = this.queryBuilder1.getModel().toString(true);
        }
        else
        {
            query = this.jEditorPaneSQL.getText();
        }
        
        this.setDialogResult(javax.swing.JOptionPane.OK_OPTION);
        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_jButtonOkActionPerformed
    
    public String getQuery() {
        return query;
    }

    public void setQuery(String query) throws Exception {
        
        final QueryModel qm = SQLParser.toQueryModel(query);
        
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                if (isVisible())
                {
                    queryBuilder1.setModel( qm );
                }
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonOk;
    private javax.swing.JEditorPane jEditorPaneSQL;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private nickyb.sqleonardo.querybuilder.QueryBuilder queryBuilder1;
    // End of variables declaration//GEN-END:variables
    
    /** 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;
    }

    public boolean isInit() {
        return init;
    }

    public void setInit(boolean init) {
        this.init = init;
    }
    
}
