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

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
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 SettingsDialog extends TitleAreaDialog {

	private Text textSVNLocation;
	private Text textWorkingDirectory;
	private Text textSVNUsername;
	private Text textSVNPassword;
	private Text textMySQLHost;
	private Text textMySQLDb;
	private Text textMySQLUsername;
	private Text textMySQLPassword;
	private Text textPdflatex;
	private Text textResearchGroup;
	private Text textResearchGroupUrl;
	private Combo cboUseSSL;

	public SettingsDialog(Shell parentShell) {
		super(parentShell);
		this.getFileContents();
		setTitle("Settings");
	}

	@Override
	protected Control createContents(Composite parent) {
		Control contents = super.createContents(parent);
		setTitle("Settings");
		setMessage("Change the Settings to match your Settings",
				IMessageProvider.INFORMATION);
		return contents;
	}

	@Override
	protected Control createDialogArea(Composite parent) {

		GridLayout layout = new GridLayout();
		layout.numColumns = 2;
		parent.setLayout(layout);
		Label label1 = new Label(parent, SWT.NONE);
		label1.setText("SVN Location:");
		Text textbox1 = new Text(parent, SWT.BORDER);
		textbox1.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
				| GridData.HORIZONTAL_ALIGN_FILL));
		textSVNLocation = textbox1;

		Label label2 = new Label(parent, SWT.NONE);
		label2.setText("Working Directory:");
		Text textbox2 = new Text(parent, SWT.BORDER);
		textbox2.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
				| GridData.HORIZONTAL_ALIGN_FILL));
		textWorkingDirectory = textbox2;

		Label label3 = new Label(parent, SWT.NONE);
		label3.setText("SVN Username:");
		Text textbox3 = new Text(parent, SWT.BORDER);
		textbox3.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
				| GridData.HORIZONTAL_ALIGN_FILL));
		textSVNUsername = textbox3;

		Label label4 = new Label(parent, SWT.NONE);
		label4.setText("SVN Password:");
		Text textbox4 = new Text(parent, SWT.BORDER | SWT.PASSWORD);
		textbox4.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
				| GridData.HORIZONTAL_ALIGN_FILL));
		textSVNPassword = textbox4;

		Label label5 = new Label(parent, SWT.NONE);
		label5.setText("MySQL Host:");
		Text textbox5 = new Text(parent, SWT.BORDER);
		textbox5.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
				| GridData.HORIZONTAL_ALIGN_FILL));
		textMySQLHost = textbox5;

		Label label6 = new Label(parent, SWT.NONE);
		label6.setText("MySQL Database:");
		Text textbox6 = new Text(parent, SWT.BORDER);
		textbox6.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
				| GridData.HORIZONTAL_ALIGN_FILL));
		textMySQLDb = textbox6;

		Label label7 = new Label(parent, SWT.NONE);
		label7.setText("MySQL Username:");
		Text textbox7 = new Text(parent, SWT.BORDER);
		textbox7.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
				| GridData.HORIZONTAL_ALIGN_FILL));
		textMySQLUsername = textbox7;

		Label label8 = new Label(parent, SWT.NONE);
		label8.setText("MySQL Password:");
		Text textbox8 = new Text(parent, SWT.BORDER | SWT.PASSWORD);
		textbox8.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
				| GridData.HORIZONTAL_ALIGN_FILL));
		textMySQLPassword = textbox8;

		Label label9 = new Label(parent, SWT.NONE);
		label9.setText("Use SSL:");
		Combo combo1 = new Combo(parent, SWT.LEFT);
		combo1.add("No SSL");
		combo1.add("Use SSL");
		combo1.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
				| GridData.HORIZONTAL_ALIGN_FILL));
		cboUseSSL = combo1;

		Label label10 = new Label(parent, SWT.NONE);
		label10.setText("PDFLatex Path");
		Text textbox10 = new Text(parent, SWT.BORDER);
		textbox10.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
				| GridData.HORIZONTAL_ALIGN_FILL));
		textPdflatex = textbox10;

		Label label11 = new Label(parent, SWT.NONE);
		label11.setText("Research Group");
		textResearchGroup = new Text(parent, SWT.BORDER);
		textResearchGroup.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
				| GridData.HORIZONTAL_ALIGN_FILL));

		Label label12 = new Label(parent, SWT.NONE);
		label12.setText("Research Group Url");
		textResearchGroupUrl = new Text(parent, SWT.BORDER);
		textResearchGroupUrl.setLayoutData(new GridData(
				GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL));

		Settings settings = Settings.getInstance();
		if (settings.isMysqlSSL())
			cboUseSSL.select(1);
		else
			cboUseSSL.select(0);

		textSVNLocation.setText(settings.getSvnLocation());
		textWorkingDirectory.setText(settings.getWorkingDirectory());
		textSVNUsername.setText(settings.getSvnUsername());
		textSVNPassword.setText(settings.getSvnPassword());
		textMySQLHost.setText(settings.getMysqlHost());
		textMySQLDb.setText(settings.getMysqlDb());
		textMySQLUsername.setText(settings.getMysqlUsername());
		textMySQLPassword.setText(settings.getMysqlPassword());
		textPdflatex.setText(settings.getPdfLatexPath());
		textResearchGroup.setText(settings.getResearchGroup());
		textResearchGroupUrl.setText(settings.getResearchGroupUrl());

		GridData gd = new GridData(GridData.HORIZONTAL_ALIGN_END);
		gd.horizontalSpan = 1;

		return parent;

	}

	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		((GridLayout) parent.getLayout()).numColumns = 2;

		GridData buttonlayout = new GridData(SWT.LEFT, SWT.BEGINNING, false,
				false);
		buttonlayout.minimumWidth = 200;
		Button button = new Button(parent, SWT.PUSH);
		button.setText("OK");
		button.setFont(JFaceResources.getDialogFont());
		button.setLayoutData(buttonlayout);
		button.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				if (textSVNLocation.getText().length() != 0
						&& textWorkingDirectory.getText().length() != 0
						&& textSVNUsername.getText().length() != 0
						&& textSVNPassword.getText().length() != 0) {
		
					Settings settings = Settings.getInstance();
					
					settings.setSvnLocation(textSVNLocation.getText());
					settings.setWorkingDirectory(textWorkingDirectory.getText());
					settings.setSvnUsername(textSVNUsername.getText());
					settings.setSvnPassword(textSVNPassword.getText());
					settings.setMysqlHost(textMySQLHost.getText());
					settings.setMysqlDb(textMySQLDb.getText());
					settings.setMysqlUsername(textMySQLUsername.getText());
					settings.setMysqlPassword(textMySQLPassword.getText());
					settings.setPdfLatexPath(textPdflatex.getText());
					settings.setResearchGroup(textResearchGroup.getText());
					settings.setResearchGroupUrl(textResearchGroupUrl.getText());
					
					if (cboUseSSL.getSelectionIndex() == 1)
						settings.setMysqlSSL(true);
					else
						settings.setMysqlSSL(false);

					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;
					}
					setFileContents();
					close();

				} else {
					setErrorMessage("Please fill out all fields");
				}
			}
		});
		Button cancel = new Button(parent, SWT.PUSH);
		cancel.setText("Cancel");
		cancel.setFont(JFaceResources.getDialogFont());
		cancel.setLayoutData(buttonlayout);
		cancel.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				close();
			}
		});
	}

	private void getFileContents() {
		Properties properties = new Properties();
		File file = new File(System.getProperty("user.home")
				+ "/.exerciseSettings");
		if (file.exists()) {
			try {
				properties.load(new FileInputStream(file));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				Settings settings = Settings.getInstance();
				settings.setSvnLocation(properties.getProperty("svnLocation"));
				settings.setWorkingDirectory(properties.getProperty("workingDirectory"));
				settings.setSvnUsername(properties.getProperty("svnUsername"));
				settings.setSvnPassword(properties.getProperty("svnPassword"));
				settings.setMysqlHost(properties.getProperty("mySQLHost"));
				settings.setMysqlDb(properties.getProperty("mySQLDb"));
				settings.setMysqlUsername(properties.getProperty("mySQLUsername"));
				settings.setMysqlPassword(properties.getProperty("mySQLPassword"));
				settings.setMysqlSSL(Boolean.parseBoolean(properties
						.getProperty("mySQLcheckSSL")));
				settings.setPdfLatexPath(properties.getProperty("pdfLatexPath"));
				settings.setResearchGroup(properties.getProperty("researchGroup"));
				settings.setResearchGroupUrl(properties.getProperty("researchGroupUrl"));
			} catch (Exception ex) {
			}
		}
	}

	private void setFileContents() {
		Properties properties = new Properties();
		File file = new File(System.getProperty("user.home")
				+ "/.exerciseSettings");
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
				return;
			}
		}
		Settings settings = Settings.getInstance();

		properties.setProperty("svnLocation", settings.getSvnLocation());
		properties.setProperty("workingDirectory", settings.getWorkingDirectory());
		properties.setProperty("svnUsername", settings.getSvnUsername());
		properties.setProperty("svnPassword", settings.getSvnPassword());
		properties.setProperty("mySQLHost", settings.getMysqlHost());
		properties.setProperty("mySQLDb", settings.getMysqlDb());
		properties.setProperty("mySQLUsername", settings.getMysqlUsername());
		properties.setProperty("mySQLPassword", settings.getMysqlPassword());
		properties.setProperty("mySQLcheckSSL", String.valueOf(settings.isMysqlSSL()));
		properties.setProperty("pdfLatexPath", settings.getPdfLatexPath());
		properties.setProperty("researchGroup", settings.getResearchGroup());
		properties.setProperty("researchGroupUrl", settings.getResearchGroupUrl());

		try {
			properties.store(new FileOutputStream(file),
					"SVN and other Settings included");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}