package de.ugoe.cs.swe.memos.gui.menu;

import java.sql.SQLException;

import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.commands.IHandler;
import org.eclipse.core.commands.IHandlerListener;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

import de.ugoe.cs.swe.memos.SettingsManager;
import de.ugoe.cs.swe.memos.Utils;
import de.ugoe.cs.swe.memos.database.Connector;
import de.ugoe.cs.swe.memos.database.DatabaseException;
import de.ugoe.cs.swe.memos.gui.dialogs.SettingsDialog;

public class propertiesHandler implements IHandler {
	private static boolean enabled = true;

	public static void setEnabled(boolean state) {
		enabled = state;
	}

	@Override
	public void addHandlerListener(IHandlerListener handlerListener) {
		// TODO Auto-generated method stub

	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub

	}

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException {
		SettingsDialog sd = new SettingsDialog(PlatformUI.getWorkbench()
				.getActiveWorkbenchWindow().getShell());
		SettingsManager sm = SettingsManager.getInstance();
		boolean reOpen = true;

		while (reOpen) {
			if (sd.open() == IDialogConstants.OK_ID) {
				if (!sd.getURI().equals(sm.getDatabaseURI())
						|| !sd.getUsername().equals(sm.getUsername())
						|| !sd.getPassword().equals(sm.getPassword())
						|| sd.getUseSSL() != sm.getSSLEnabled()
						|| !sd.getHSQLDirectory().equals(sm.getHSQLFilename())
						|| sd.getDbTyp() != sm.getDBType()) {

					String oldDatabaseURI = sm.getDatabaseURI();
					String oldUsername = sm.getUsername();
					String oldPassword = sm.getPassword();
					boolean oldUseSSL = sm.getSSLEnabled();
					// String oldSSLKeyName = sm.getSSLKeyName();
					String oldHSQLFilename = sm.getHSQLFilename();
					SettingsManager.DatabaseType oldDBType = sm.getDBType();

					sm.setDatabaseURI(sd.getURI());
					sm.setUsername(sd.getUsername());
					sm.setPassword(sd.getPassword());
					sm.setSSLEnabled(sd.getUseSSL());
					// sm.setSSLKeyName(sd.getKeyPath());
					sm.setHSQLFilename(sd.getHSQLDirectory());
					sm.setDBType(sd.getDbTyp());

					// first close the connection
					try {
						Connector.closeConnection();
					} catch (DatabaseException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					} catch (SQLException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

					if (Connector.getConnection() != null) {
						boolean connectionIsClosed = false;
						try {
							connectionIsClosed = Connector.getConnection()
									.isClosed();
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						if (!connectionIsClosed) {
							CTabFolder tabFolder = Utils.getMainView()
									.getTabFolder();
							int itemCount = tabFolder.getItems().length;

							if (itemCount > 1) {
								MessageBox mb = new MessageBox(new Shell(),
										SWT.YES | SWT.NO | SWT.ICON_WARNING);
								mb.setText("Tabs schließen?");
								mb
										.setMessage("Das Ändern der URI wird alle aktiven Tabs schließen. Fortfahren?");
								int answer = mb.open();
								if (answer == SWT.YES) {
									boolean first = true;
									for (CTabItem item : tabFolder.getItems()) {
										if (!first)
											item.dispose();
										first = false;
									}
								} else if (answer == SWT.NO) {
									reconnectToOldDatabase(sm, oldDatabaseURI,
											oldUsername, oldPassword,
											oldUseSSL, oldHSQLFilename,
											oldDBType);
									return null;
								}
							}
							Utils.getMainView().getCatBrowser()
									.refreshCatTree();

							// TODO: SOMEONE FIX THIS *!$!"§
							// sm.setSSLKeyName(sd.getKeyPath().getText());

							sm.saveSettingsToFile();
							reOpen = false;
						} else {
							reconnectToOldDatabase(sm, oldDatabaseURI,
									oldUsername, oldPassword, oldUseSSL,
									oldHSQLFilename, oldDBType);
							reOpen = true;
						}
					} else {
						reconnectToOldDatabase(sm, oldDatabaseURI, oldUsername,
								oldPassword, oldUseSSL, oldHSQLFilename,
								oldDBType);
						reOpen = true;
					}
				} else
					reOpen = false;
				sm.setImport_Path(sd.getImportPath());
				sm.setExport_Path(sd.getExportPath());
				sm.setLockTimeout(sd.getTimeout());
			}
			else
				reOpen = false;
		}
		return null;
	}

	private void reconnectToOldDatabase(SettingsManager sm,
			String oldDatabaseURI, String oldUsername, String oldPassword,
			boolean oldUseSSL, String oldHSQLFilename,
			SettingsManager.DatabaseType oldDBType) {
		sm.setDatabaseURI(oldDatabaseURI);
		sm.setUsername(oldUsername);
		sm.setPassword(oldPassword);
		sm.setSSLEnabled(oldUseSSL);
		sm.setHSQLFilename(oldHSQLFilename);
		sm.setDBType(oldDBType);
		// reopen connection
		Connector.getConnection();

		MessageBox mb = new MessageBox(new Shell(), SWT.OK | SWT.ICON_WARNING);
		mb.setText("Verbindung fehlgeschlagen");
		mb
				.setMessage("Die neue Datenbank URI scheint fehlerhaft zu sein. Die alte URI wird weiterhin benutzt.");
		mb.open();
	}

	@Override
	public boolean isEnabled() {
		// TODO Auto-generated method stub
		return enabled;
	}

	@Override
	public boolean isHandled() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void removeHandlerListener(IHandlerListener handlerListener) {
		// TODO Auto-generated method stub

	}

}
