package de.ugoe.cs.swe.exercises.settings;

import java.sql.DriverManager;
import java.sql.SQLException;

import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
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.misc.Model;

public class SettingsDialog2 extends TitleAreaDialog {
	private SettingsComposite settingsComposite;
	private SettingsProfileComposite settingsProfileComposite;
	private TabItem tbtmSettings;
	private TabItem tbtmProfiledSettings;
	private String activeTabItem;
	private TabFolder tabFolder;

	public SettingsDialog2(Shell parentShell) {
		super(parentShell);
		Settings.getInstance().load();
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		setTitle("Settings");
		Composite area = (Composite) super.createDialogArea(parent);
		{
			tabFolder = new TabFolder(area, SWT.NONE);
			tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
					true, 1, 1));
			{
				tbtmSettings = new TabItem(tabFolder, SWT.NONE);
				tbtmSettings.setText("Settings");
				{
					settingsComposite = new SettingsComposite(tabFolder,
							SWT.NONE);
					tbtmSettings.setControl(settingsComposite);
				}
			}
			{
				tbtmProfiledSettings = new TabItem(tabFolder, SWT.NONE);
				tbtmProfiledSettings.setText("Profiled Settings");
				{
					settingsProfileComposite = new SettingsProfileComposite(
							tabFolder, SWT.NONE);
					tbtmProfiledSettings.setControl(settingsProfileComposite);
				}
			}
		}
		tabFolder.addSelectionListener(new SelectionListener() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				activeTabItem = ((TabItem) e.item).getText();
			}

			@Override
			public void widgetDefaultSelected(SelectionEvent e) {
			}
		});
		tabFolder.setSelection(tbtmSettings);
		activeTabItem = tbtmSettings.getText();

		updateWidgets();

		return area;
	}

	private void updateWidgets() {
		Settings settings = Settings.getInstance();
		if (settings.isMysqlSSL()) {
			settingsComposite.getMysqlSSLCombo().select(1);
			settingsProfileComposite.getMysqlSSLCombo().select(1);
		} else {
			settingsComposite.getMysqlSSLCombo().select(0);
			settingsProfileComposite.getMysqlSSLCombo().select(0);
		}

		settingsComposite.getSvnLocationText().setText(
				settings.getSvnLocation());
		settingsComposite.getMysqlHostText().setText(settings.getMysqlHost());
		settingsComposite.getMysqlDatabaseText().setText(settings.getMysqlDb());
		settingsComposite.getResearchGroupText().setText(
				settings.getResearchGroup());
		settingsComposite.getResearchGroupUrlText().setText(
				settings.getResearchGroupUrl());

		settingsComposite.getSvnWorkingCopyText().setText(
				settings.getWorkingDirectory());
		settingsProfileComposite.getSvnWorkingCopyText().setText(
				settings.getWorkingDirectory());

		settingsComposite.getSvnUsernameText().setText(
				settings.getSvnUsername());
		settingsProfileComposite.getSvnUsernameText().setText(
				settings.getSvnUsername());

		settingsComposite.getSvnPasswordText().setText(
				settings.getSvnPassword());
		settingsProfileComposite.getSvnPasswordText().setText(
				settings.getSvnPassword());

		settingsComposite.getMysqlUsernameText().setText(
				settings.getMysqlUsername());
		settingsProfileComposite.getMysqlUsernameText().setText(
				settings.getMysqlUsername());

		settingsComposite.getMysqlPasswordText().setText(
				settings.getMysqlPassword());
		settingsProfileComposite.getMysqlPasswordText().setText(
				settings.getMysqlPassword());

		settingsComposite.getPdfLatexText().setText(settings.getPdfLatexPath());
		settingsProfileComposite.getPdfLatexText().setText(
				settings.getPdfLatexPath());
	}

	protected void okPressed() {
		updateSettings();
		Settings settings = Settings.getInstance();

		// validate settings
		try {
			DAVRepositoryFactory.setup();
			SVNURL url = SVNURL.parseURIDecoded(settings.getSvnLocation());
			SVNRepository repository = SVNRepositoryFactory.create(url);
			ISVNAuthenticationManager authManager = SVNWCUtil
					.createDefaultAuthenticationManager(settings
							.getSvnUsername(), settings.getSvnPassword());
			((SVNRepository) repository).setAuthenticationManager(authManager);
			repository.testConnection();

		} catch (SVNException ex) {
			setErrorMessage(ex.getMessage());
			return;
		}

		System.setProperty("javax.net.ssl.trustStorePassword", settings
				.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://" + settings.getMysqlHost() + "/"
					+ settings.getMysqlDb() + "?useSSL="
					+ String.valueOf(settings.isMysqlSSL());
			DriverManager.getConnection(url, settings.getMysqlUsername(),
					settings.getMysqlPassword());
		} catch (SQLException ex) {
			setErrorMessage(ex.getMessage());
			return;
		} catch (Exception ex2) {
			setErrorMessage(ex2.getMessage());
			return;
		}

		// save settings
		Settings.getInstance().save();
		setReturnCode(OK);
		close();
	}

	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,
				true);
		createButton(parent, IDialogConstants.CANCEL_ID,
				IDialogConstants.CANCEL_LABEL, false);
	}

	private void updateSettings() {
		Settings settings = Settings.getInstance();

		if (activeTabItem.contains("Profiled Settings")) {
			settings.setWorkingDirectory(settingsProfileComposite
					.getSvnWorkingCopyText().getText());
			settings.setSvnUsername(settingsProfileComposite
					.getSvnUsernameText().getText());
			settings.setSvnPassword(settingsProfileComposite
					.getSvnPasswordText().getText());
			settings.setMysqlUsername(settingsProfileComposite
					.getMysqlUsernameText().getText());
			settings.setMysqlPassword(settingsProfileComposite
					.getMysqlPasswordText().getText());
			settings.setPdfLatexPath(settingsProfileComposite.getPdfLatexText()
					.getText());
			if (settingsProfileComposite.getMysqlSSLCombo().getSelectionIndex() == 1) {
				settings.setMysqlSSL(true);
			} else {
				settings.setMysqlSSL(false);
			}
		} else {
			settings.setSvnLocation(settingsComposite.getSvnLocationText()
					.getText());
			settings.setMysqlHost(settingsComposite.getMysqlHostText()
					.getText());
			settings.setMysqlDb(settingsComposite.getMysqlDatabaseText()
					.getText());
			settings.setResearchGroup(settingsComposite.getResearchGroupText()
					.getText());
			settings.setResearchGroupUrl(settingsComposite
					.getResearchGroupUrlText().getText());

			settings.setWorkingDirectory(settingsComposite
					.getSvnWorkingCopyText().getText());
			settings.setSvnUsername(settingsComposite.getSvnUsernameText()
					.getText());
			settings.setSvnPassword(settingsComposite.getSvnPasswordText()
					.getText());
			settings.setMysqlUsername(settingsComposite.getMysqlUsernameText()
					.getText());
			settings.setMysqlPassword(settingsComposite.getMysqlPasswordText()
					.getText());
			settings.setPdfLatexPath(settingsComposite.getPdfLatexText()
					.getText());
			if (settingsComposite.getMysqlSSLCombo().getSelectionIndex() == 1) {
				settings.setMysqlSSL(true);
			} else {
				settings.setMysqlSSL(false);
			}
		}
	}

	@Override
	protected Point getInitialSize() {
		return new Point(554, 547);
	}

}
