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

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 Combo cboUseSSL;
	private String svnLocation = "";
	private String workingDirectory = "";
	private String svnUsername = "";
	private String svnPassword = "";
	private String mySQLHost = "";
	private String mySQLDb = "";
	private String mySQLUsername = "";
	private String mySQLPassword = "";
	private String myPDFLatexPath = "";
	private boolean mySQLcheckSSL = false;

	public boolean hasSettings() {
		if (svnLocation == "" || workingDirectory == "" || svnUsername == ""
				|| svnPassword == "" || mySQLHost == "" || mySQLDb == ""
				|| mySQLUsername == "" || mySQLPassword == ""
				|| myPDFLatexPath == "") {
			return false;
		}
		return true;
	}

	public String getmyPDFLatexPath() {
		return myPDFLatexPath;
	}

	public void setmyPDFLatexPath(String myPDFLatexPath) {
		this.myPDFLatexPath = myPDFLatexPath;
	}

	public String getSVNLocation() {
		return svnLocation;
	}

	public String getWorkingDirectory() {
		return workingDirectory;
	}

	public String getSVNUsername() {
		return svnUsername;
	}

	public String getSVNPassword() {
		return svnPassword;
	}

	public String getMySQLHost() {
		return mySQLHost;
	}

	public String getMySQLDb() {
		return mySQLDb;
	}

	public String getMySQLUsername() {
		return mySQLUsername;
	}

	public String getMySQLPassword() {
		return mySQLPassword;
	}

	public boolean isMySQLcheckSSL() {
		return mySQLcheckSSL;
	}

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

	@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;

		if (mySQLcheckSSL)
			cboUseSSL.select(1);
		else
			cboUseSSL.select(0);

		textSVNLocation.setText(svnLocation);
		textWorkingDirectory.setText(workingDirectory);
		textSVNUsername.setText(svnUsername);
		textSVNPassword.setText(svnPassword);
		textMySQLHost.setText(mySQLHost);
		textMySQLDb.setText(mySQLDb);
		textMySQLUsername.setText(mySQLUsername);
		textMySQLPassword.setText(mySQLPassword);
		textPdflatex.setText(myPDFLatexPath);

		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) {
					svnLocation = textSVNLocation.getText();
					workingDirectory = textWorkingDirectory.getText();
					svnUsername = textSVNUsername.getText();
					svnPassword = textSVNPassword.getText();
					mySQLHost = textMySQLHost.getText();
					mySQLDb = textMySQLDb.getText();
					mySQLUsername = textMySQLUsername.getText();
					mySQLPassword = textMySQLPassword.getText();
					myPDFLatexPath = textPdflatex.getText();

					if (cboUseSSL.getSelectionIndex() == 1)
						mySQLcheckSSL = true;
					else
						mySQLcheckSSL = false;

					try {
						DAVRepositoryFactory.setup();
						SVNURL url = SVNURL.parseURIDecoded(svnLocation);
						SVNRepository repository = SVNRepositoryFactory
								.create(url);
						ISVNAuthenticationManager authManager = SVNWCUtil
								.createDefaultAuthenticationManager(
										svnUsername, svnPassword);
						((SVNRepository) repository)
								.setAuthenticationManager(authManager);
						repository.testConnection();

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

					System.setProperty("javax.net.ssl.trustStorePassword",
							mySQLPassword);
					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://" + mySQLHost + "/"
								+ mySQLDb + "?useSSL="
								+ String.valueOf(mySQLcheckSSL);
						DriverManager.getConnection(url, mySQLUsername,
								mySQLPassword);
					} 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 settings = new Properties();
		File file = new File(System.getProperty("user.home")
				+ "/.exerciseSettings");
		if (!file.exists()) {
			svnLocation = "";
			workingDirectory = "";
			svnUsername = "";
			svnPassword = "";
			mySQLHost = "";
			mySQLDb = "";
			mySQLUsername = "";
			mySQLPassword = "";
			mySQLcheckSSL = false;
			myPDFLatexPath = "";
		} else {
			try {
				settings.load(new FileInputStream(file));
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				if (settings.getProperty("svnLocation") != null)
					svnLocation = settings.getProperty("svnLocation");
				if (settings.getProperty("workingDirectory") != null)
					workingDirectory = settings.getProperty("workingDirectory");
				if (settings.getProperty("svnUsername") != null)
					svnUsername = settings.getProperty("svnUsername");
				if (settings.getProperty("svnPassword") != null)
					svnPassword = settings.getProperty("svnPassword");
				if (settings.getProperty("mySQLHost") != null)
					mySQLHost = settings.getProperty("mySQLHost");
				if (settings.getProperty("mySQLDb") != null)
					mySQLDb = settings.getProperty("mySQLDb");
				if (settings.getProperty("mySQLUsername") != null)
					mySQLUsername = settings.getProperty("mySQLUsername");
				if (settings.getProperty("mySQLPassword") != null)
					mySQLPassword = settings.getProperty("mySQLPassword");
				if (settings.getProperty("mySQLcheckSSL") != null)
					mySQLcheckSSL = Boolean.parseBoolean(settings
							.getProperty("mySQLcheckSSL"));
				if (settings.getProperty("mySQLcheckSSL") != null)
					myPDFLatexPath = settings.getProperty("myPDFLatexPath");
			} catch (Exception ex) {
				svnLocation = "";
				workingDirectory = "";
				svnUsername = "";
				svnPassword = "";
				mySQLHost = "";
				mySQLDb = "";
				mySQLUsername = "";
				mySQLPassword = "";
				mySQLcheckSSL = false;
				myPDFLatexPath = "";
			}
		}
	}

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

		settings.setProperty("svnLocation", svnLocation);
		settings.setProperty("workingDirectory", workingDirectory);
		settings.setProperty("svnUsername", svnUsername);
		settings.setProperty("svnPassword", svnPassword);
		settings.setProperty("mySQLHost", mySQLHost);
		settings.setProperty("mySQLDb", mySQLDb);
		settings.setProperty("mySQLUsername", mySQLUsername);
		settings.setProperty("mySQLPassword", mySQLPassword);
		settings.setProperty("mySQLcheckSSL", String.valueOf(mySQLcheckSSL));
		settings.setProperty("myPDFLatexPath", myPDFLatexPath);

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

}