/*
 * Copyright (C) 2008 Andreas Schnaiter
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA
 */
package org.afraid.poison.db2php;

import java.util.LinkedHashSet;
import java.util.Set;
import javax.swing.DefaultListModel;
import javax.swing.JPanel;
import org.afraid.poison.common.CollectionUtil;
import org.afraid.poison.db2php.generator.Table;
import org.afraid.poison.db2php.generator.TableEvent;
import org.afraid.poison.db2php.generator.TableListener;
import org.netbeans.api.db.explorer.ConnectionManager;
import org.netbeans.api.db.explorer.DatabaseConnection;
import org.netbeans.api.db.explorer.support.DatabaseExplorerUIs;

public final class PhpClassVisualPanelTableSelection extends JPanel {

	/** Creates new form PhpClassVisualPanelTableSelection */
	public PhpClassVisualPanelTableSelection() {
		initComponents();
		DatabaseExplorerUIs.connect(connectionSelector, ConnectionManager.getDefault());
	}

	@Override
	public String getName() {
		return "Choose Tables";
	}

	public Set<Table> getSelected() {
		LinkedHashSet<Table> selected=new LinkedHashSet<Table>();
		if (null==getTablesSelection()) {
			return selected;
		}
		selected.addAll(CollectionUtil.filterType(Table.class, getTablesSelection().getSelectedValues()));
		return selected;
	}

	@Override
	public boolean isValid() {
		return getSelected().size()>0;
	}

	/** 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() {

        connectionSelector = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablesSelection = new javax.swing.JList();

        connectionSelector.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectionSelectorActionPerformed(evt);
            }
        });
        connectionSelector.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                connectionSelectorPropertyChange(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(PhpClassVisualPanelTableSelection.class, "PhpClassVisualPanelTableSelection.jLabel1.text")); // NOI18N

        tablesSelection.setCellRenderer(new org.afraid.poison.db2php.TablesListCellRenderer());
        tablesSelection.setEnabled(false);
        jScrollPane1.setViewportView(tablesSelection);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 492, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(connectionSelector, 0, 415, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(connectionSelector, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 259, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

	private void connectionSelectorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectionSelectorActionPerformed
		// TODO add your handling code here:
		
		final DatabaseConnection conn=(DatabaseConnection) getConnectionSelector().getSelectedItem();
		if (null!=conn) {
			//tablesModel.addElement(conn.getDisplayName());
			ConnectionManager.getDefault().showConnectionDialog(conn);
			new Thread(new Runnable() {

				@Override
				public void run() {
					final DefaultListModel tablesModelWaiting=new DefaultListModel();
					getTablesSelection().setEnabled(false);
					tablesModelWaiting.addElement("Please wait ...");
					DefaultListModel tablesModel=new DefaultListModel();
					getTablesSelection().setModel(tablesModelWaiting);
					Set<Table> tables=Table.getTables(conn.getJDBCConnection(), new TableListener() {

						@Override
						public void tableStatusChanged(TableEvent te) {
							tablesModelWaiting.addElement(te.getTable());
						}
					});
					if (!tables.isEmpty()) {
						getTablesSelection().setEnabled(true);
						for (Table t : tables) {
							tablesModel.addElement(t);
						}
						getTablesSelection().setModel(tablesModel);
					} else {
						getTablesSelection().setEnabled(false);
						tablesModel.addElement("Could not find any tables ...");
						getTablesSelection().setModel(tablesModel);
					}
				}
			}).start();

		} else {
			getTablesSelection().setEnabled(false);
		}
	}//GEN-LAST:event_connectionSelectorActionPerformed

	private void connectionSelectorPropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_connectionSelectorPropertyChange
		// TODO add your handling code here:
	}//GEN-LAST:event_connectionSelectorPropertyChange
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox connectionSelector;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JList tablesSelection;
    // End of variables declaration//GEN-END:variables

	/**
	 * @return the connectionSelector
	 */
	public javax.swing.JComboBox getConnectionSelector() {
		return connectionSelector;
	}

	/**
	 * @param connectionSelector the connectionSelector to set
	 */
	public void setConnectionSelector(javax.swing.JComboBox connectionSelector) {
		this.connectionSelector=connectionSelector;
	}

	/**
	 * @return the tablesSelection
	 */
	public javax.swing.JList getTablesSelection() {
		return tablesSelection;
	}

	/**
	 * @param tablesSelection the tablesSelection to set
	 */
	public void setTablesSelection(javax.swing.JList tablesSelection) {
		this.tablesSelection=tablesSelection;
	}
}
