package de.ugoe.cs.swe.exercises;

import java.io.File;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.io.dav.DAVRepositoryFactory;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.core.io.SVNRepositoryFactory;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

import de.ugoe.cs.swe.exercises.exercise.ExerciseSVN;
import de.ugoe.cs.swe.exercises.misc.Model;
import de.ugoe.cs.swe.exercises.svn.SettingsDialog;

/**
 * This class controls all aspects of the application's execution
 */
public class Application implements IApplication {

	/*
	 * (non-Javadoc)
	 * 
	 * @seeorg.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.
	 * IApplicationContext)
	 */
	public Object start(IApplicationContext context) {
		Display display = PlatformUI.createDisplay();
		SettingsDialog settingsDialog = new SettingsDialog(new Shell());
		/* try{ */
		if (!settingsDialog.hasSettings())
			settingsDialog.open();
		/*
		 * } catch (NullPointerException ex){ settingsDialog.open(); } catch
		 * (IllegalArgumentException ex) { settingsDialog.open(); } catch
		 * (Exception ex) { settingsDialog.open(); }
		 */
		try {
			DAVRepositoryFactory.setup();
			SVNURL url = SVNURL
					.parseURIDecoded(settingsDialog.getSVNLocation());
			SVNRepository repository = SVNRepositoryFactory.create(url);
			ISVNAuthenticationManager authManager = SVNWCUtil
					.createDefaultAuthenticationManager(settingsDialog
							.getSVNUsername(), settingsDialog.getSVNPassword());
			((SVNRepository) repository).setAuthenticationManager(authManager);
			repository.testConnection();
		} catch (SVNException ex) {
			settingsDialog.open();
			try {
				DAVRepositoryFactory.setup();
				SVNURL url = SVNURL.parseURIDecoded(settingsDialog
						.getSVNLocation());
				SVNRepository repository = SVNRepositoryFactory.create(url);
				ISVNAuthenticationManager authManager = SVNWCUtil
						.createDefaultAuthenticationManager(settingsDialog
								.getSVNUsername(), settingsDialog
								.getSVNPassword());
				((SVNRepository) repository)
						.setAuthenticationManager(authManager);
				repository.testConnection();
			} catch (SVNException ex1) {
				return null;
			}
		}

		System.setProperty("javax.net.ssl.trustStorePassword", settingsDialog
				.getMySQLPassword());
		String path = Model.class.getProtectionDomain().getCodeSource()
				.getLocation().getPath();
		if (path.endsWith("bin/"))
			path = path.replaceFirst("bin/$", "");
		path += "keystore";
		System.setProperty("javax.net.ssl.trustStore", path);

		try {
			// Step 1: Load the JDBC driver.
			Class.forName("com.mysql.jdbc.Driver").newInstance();
			// Step 2: Establish the connection to the database.
			String url = "jdbc:mysql://" + settingsDialog.getMySQLHost() + "/"
					+ settingsDialog.getMySQLDb() + "?useSSL="
					+ String.valueOf(settingsDialog.isMySQLcheckSSL());
			DriverManager.getConnection(url, settingsDialog
					.getMySQLUsername(), settingsDialog.getMySQLPassword());
		} catch (SQLException ex) {
			settingsDialog.open();
			try {
				// Step 1: Load the JDBC driver.
				Class.forName("com.mysql.jdbc.Driver").newInstance();
				// Step 2: Establish the connection to the database.
				String url = "jdbc:mysql://" + settingsDialog.getMySQLHost()
						+ "/" + settingsDialog.getMySQLDb() + "?useSSL="
						+ String.valueOf(settingsDialog.isMySQLcheckSSL());
				DriverManager.getConnection(url,
						settingsDialog.getMySQLUsername(), settingsDialog
								.getMySQLPassword());
			} catch (SQLException ex2) {
				return null;
			} catch (Exception ex2) {
				return null;
			}
		} catch (Exception ex2) {
			return null;
		}

		File file = new File(System.getProperty("user.home")
				+ "/.exerciseSettings");
		if (file.exists()) {
			try {
				ExerciseSVN.SVNCheckout();
				int returnCode = PlatformUI.createAndRunWorkbench(display,
						new ApplicationWorkbenchAdvisor());
				if (returnCode == PlatformUI.RETURN_RESTART) {
					return IApplication.EXIT_RESTART;
				}
				return IApplication.EXIT_OK;

			} finally {
				display.dispose();
			}
		}

		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.equinox.app.IApplication#stop()
	 */
	public void stop() {
		final IWorkbench workbench = PlatformUI.getWorkbench();
		if (workbench == null)
			return;
		final Display display = workbench.getDisplay();
		display.syncExec(new Runnable() {
			public void run() {
				if (!display.isDisposed())
					workbench.close();
			}
		});
	}
}
