/*
 * Created on 31.05.2004
 *
 * 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 2 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.
 * 
 */
package networkconsole.ui;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import networkconsole.datamodel.EntryListException;
import networkconsole.datamodel.JdbcEntryList;
import networkconsole.datamodel.LdapHostEntryList;
import networkconsole.datamodel.LdapUserEntryList;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.FocusAdapter;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

/**
 * @author Eugene Prokopiev <eugene_prokopiev@mail.ru>
 * 
 */
public class ConnectionDialog extends TitleAreaDialog {

	private Text ldapConnectionText;
	private Text ldapUserText;
	private Text ldapPasswordText;
	
	private Text jdbcConnectionText;
	private Text jdbcUserText;
	private Text jdbcPasswordText;	
	
	private Button savePasswordsButton;	
	private Text connectionMessagesText;
	
	private CTabFolder tabFolder;	
	
	public ConnectionDialog(Shell parent) {
		super(parent);
	}
	
	protected Control createDialogArea(Composite parent) {
		Composite area = (Composite) super.createDialogArea(parent);
		Composite container = new Composite(area, SWT.NONE);
		container.setLayout(new FormLayout());
		container.setLayoutData(new GridData(GridData.FILL_BOTH));
		{
			final Composite composite = new Composite(container, SWT.NONE);
			composite.setLayout(new GridLayout());
			final FormData formData = new FormData();
			formData.bottom = new FormAttachment(100, 0);
			formData.right = new FormAttachment(100, -4);
			formData.top = new FormAttachment(0, 4);
			formData.left = new FormAttachment(0, 4);
			composite.setLayoutData(formData);
			{
				tabFolder = new CTabFolder(composite, SWT.BORDER);
				tabFolder.setSelectionBackground(tabFolder.getBackground());
				tabFolder.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL));
				tabFolder.addFocusListener(new FocusAdapter() {
					public void focusGained(FocusEvent e) {
						ldapConnectionText.setFocus();
					}
				});
				{
					final CTabItem tabItem = new CTabItem(tabFolder, SWT.NONE);
					tabItem.setText("LDAP");
					tabItem.setImage(ImageDescriptor.createFromFile(getClass(), "images/tree.gif").createImage());
					{
						final Composite compositeLdap = new Composite(tabFolder, SWT.NONE);
						final GridLayout gridLayout = new GridLayout();
						gridLayout.numColumns = 2;
						gridLayout.marginWidth = 7;
						gridLayout.marginHeight = 7;
						gridLayout.horizontalSpacing = 15;
						compositeLdap.setLayout(gridLayout);
						compositeLdap.setFocus();
						tabItem.setControl(compositeLdap);
						{
							final Label label = new Label(compositeLdap, SWT.NONE);
							label.setText(NetworkConsoleWindow.translate("ui.dialog.connection.label.connection"));
						}
						{
							ldapConnectionText = new Text(compositeLdap, SWT.BORDER);
							ldapConnectionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
							ldapConnectionText.setText(NetworkConsoleWindow.properties.getProperty("connection.ldap.url"));
						}
						{
							final Label label = new Label(compositeLdap, SWT.NONE);
							label.setText(NetworkConsoleWindow.translate("ui.dialog.connection.label.user"));
						}
						{
							ldapUserText = new Text(compositeLdap, SWT.BORDER);
							ldapUserText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
							ldapUserText.setText(NetworkConsoleWindow.properties.getProperty("connection.ldap.user"));
						}
						{
							final Label label = new Label(compositeLdap, SWT.NONE);
							label.setText(NetworkConsoleWindow.translate("ui.dialog.connection.label.password"));
						}
						{
							ldapPasswordText = new Text(compositeLdap, SWT.BORDER);
							ldapPasswordText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
							ldapPasswordText.setText(NetworkConsoleWindow.properties.getProperty("connection.ldap.password"));
							ldapPasswordText.setEchoChar('*');
						}
					}
				}
				{
					final CTabItem tabItem = new CTabItem(tabFolder, SWT.NONE);
					tabItem.setText("JDBC");
					tabItem.setImage(ImageDescriptor.createFromFile(getClass(), "images/table.gif").createImage());
					{
						final Composite compositeJdbc = new Composite(tabFolder, SWT.NONE);
						final GridLayout gridLayout = new GridLayout();
						gridLayout.numColumns = 2;
						gridLayout.marginWidth = 7;
						gridLayout.marginHeight = 7;
						gridLayout.horizontalSpacing = 15;
						compositeJdbc.setLayout(gridLayout);
						tabItem.setControl(compositeJdbc);
						{
							final Label label = new Label(compositeJdbc, SWT.NONE);
							label.setText(NetworkConsoleWindow.translate("ui.dialog.connection.label.connection"));
						}
						{
							jdbcConnectionText = new Text(compositeJdbc, SWT.BORDER);
							jdbcConnectionText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
							jdbcConnectionText.setText(NetworkConsoleWindow.properties.getProperty("connection.jdbc.url"));
						}
						{
							final Label label = new Label(compositeJdbc, SWT.NONE);
							label.setText(NetworkConsoleWindow.translate("ui.dialog.connection.label.user"));
						}
						{
							jdbcUserText = new Text(compositeJdbc, SWT.BORDER);
							jdbcUserText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
							jdbcUserText.setText(NetworkConsoleWindow.properties.getProperty("connection.jdbc.user"));
						}
						{
							final Label label = new Label(compositeJdbc, SWT.NONE);
							label.setText(NetworkConsoleWindow.translate("ui.dialog.connection.label.password"));
						}
						{
							jdbcPasswordText = new Text(compositeJdbc, SWT.BORDER);
							jdbcPasswordText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
							jdbcPasswordText.setText(NetworkConsoleWindow.properties.getProperty("connection.jdbc.password"));
							jdbcPasswordText.setEchoChar('*');
						}
					}
				}
			}
			{
				savePasswordsButton = new Button(composite, SWT.CHECK);
				savePasswordsButton.setText(NetworkConsoleWindow.translate("ui.dialog.connection.label.save_passwords"));
				savePasswordsButton.setSelection(NetworkConsoleWindow.properties.getProperty("connection.save_passwords").equals("true"));
			}
			{
				final Group group = new Group(composite, SWT.NONE);
				group.setText(NetworkConsoleWindow.translate("ui.dialog.connection.label.connection_messages"));
				group.setLayoutData(new GridData(GridData.FILL_BOTH));
				group.setLayout(new GridLayout());
				{
					connectionMessagesText = new Text(group, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.WRAP);
					final GridData gridData = new GridData(GridData.FILL_BOTH);
					gridData.heightHint = 40;
					connectionMessagesText.setLayoutData(gridData);
					connectionMessagesText.setEditable(false);
				}
			}
		}
		
		setTitle(NetworkConsoleWindow.translate("ui.dialog.connection.title"));
		setMessage(NetworkConsoleWindow.translate("ui.dialog.connection.message"));
		
		tabFolder.setFocus();
		
		return area;
	}
	
	protected void createButtonsForButtonBar(Composite parent) {
		
		createButton(
			parent,
			IDialogConstants.OK_ID,
			NetworkConsoleWindow.translate("ui.dialog.ok"),
			true);
			
		createButton(
			parent,
			IDialogConstants.CANCEL_ID,
			NetworkConsoleWindow.translate("ui.dialog.cancel"),
			false);
	}
	
	protected void okPressed() {
				
		try {				
			connect();			
			saveConnectionSettings();
			super.okPressed();			
		} catch (Exception exception) {
			connectionMessagesText.append("["+exception.getClass().getName()+"] "+exception.getLocalizedMessage());
			exception.printStackTrace();
		}		
	}

	private void saveConnectionSettings() throws IOException {
		
		NetworkConsoleWindow.properties.setProperty("connection.ldap.url", ldapConnectionText.getText());
		NetworkConsoleWindow.properties.setProperty("connection.ldap.user", ldapUserText.getText());
		if (savePasswordsButton.getSelection())
			NetworkConsoleWindow.properties.setProperty("connection.ldap.password", ldapPasswordText.getText());
		else
			NetworkConsoleWindow.properties.setProperty("connection.ldap.password", "");
			
		NetworkConsoleWindow.properties.setProperty("connection.jdbc.url", jdbcConnectionText.getText());
		NetworkConsoleWindow.properties.setProperty("connection.jdbc.user", jdbcUserText.getText());
		if (savePasswordsButton.getSelection())
			NetworkConsoleWindow.properties.setProperty("connection.jdbc.password", jdbcPasswordText.getText());
		else
			NetworkConsoleWindow.properties.setProperty("connection.jdbc.password", "");
		
		if (savePasswordsButton.getSelection())
			NetworkConsoleWindow.properties.setProperty("connection.save_passwords", "true");
		else
			NetworkConsoleWindow.properties.setProperty("connection.save_passwords", "false");
		
		NetworkConsoleWindow.saveProperties();
		
		connectionMessagesText.append("Connection settings saved"+Text.DELIMITER);
	}

	private void connect() throws EntryListException, ClassNotFoundException, SQLException {
		
		connectionMessagesText.setText("");			
		connectionMessagesText.append("LDAP connection ..."+Text.DELIMITER);
		
		NetworkConsoleWindow.hosts = new LdapHostEntryList(
			ldapConnectionText.getText(),
			NetworkConsoleWindow.properties.getProperty("connection.ldap.context.hosts"),
			ldapUserText.getText(),
			ldapPasswordText.getText());
			
		NetworkConsoleWindow.users = new LdapUserEntryList(
			ldapConnectionText.getText(),
			NetworkConsoleWindow.properties.getProperty("connection.ldap.context.users"),
			ldapUserText.getText(),
			ldapPasswordText.getText());
		
		connectionMessagesText.append("LDAP connected"+Text.DELIMITER);			
		connectionMessagesText.append("JDBC connection ..."+Text.DELIMITER);
		
		Class.forName("org.firebirdsql.jdbc.FBDriver");
		Connection connection = DriverManager.getConnection(
			jdbcConnectionText.getText(), jdbcUserText.getText(), jdbcPasswordText.getText());
		boolean translation = NetworkConsoleWindow.properties.getProperty("ui.view.traffic.translate").equals("true");
		NetworkConsoleWindow.queryList = new JdbcEntryList(connection, "", translation);
		if (translation) {
			NetworkConsoleWindow.proceduresList = new JdbcEntryList(connection, "", true);
			NetworkConsoleWindow.proceduresList.setSqlProceduresList();
		}

		connectionMessagesText.append("JDBC connected"+Text.DELIMITER);
	}
	
	protected void configureShell(Shell shell) {
		
		super.configureShell(shell);
		shell.setText(NetworkConsoleWindow.translate("ui.dialog.connection.caption"));
	}

}
