package com.quantum.util.connection;

import java.sql.Connection;
import java.sql.SQLException;

import com.quantum.Messages;
import com.quantum.model.Bookmark;
import com.quantum.model.ConnectionException;
import com.quantum.model.NotConnectedException;
import com.quantum.ui.dialog.ExceptionDisplayDialog;
import com.quantum.ui.dialog.PasswordDialog;
import com.quantum.ui.dialog.SQLExceptionDialog;

import org.eclipse.swt.widgets.Shell;

/**
 * <p>This utility gets a connection from a bookmark, and handles any UI-specific
 * interactions such as providing messages to the user and/or prompting for a 
 * password.
 * 
 * @author BC Holmes
 */
public class ConnectionUtil {

    public Connection getConnection(Bookmark bookmark, Shell shell) {
        Connection connection = null;
        try {
            connection = bookmark.getConnection();
        } catch (NotConnectedException e) {
            connection = connect(bookmark, shell);
        }
        return connection;
    }

    public Connection connect(Bookmark bookmark, Shell shell) {
        Connection connection = null;
        try {
            connection = bookmark.connect(PasswordDialog.createPasswordFinder(shell));
        } catch (ConnectionException e) {
        	if (e.getCause() != null && e.getCause() instanceof SQLException) {
        		SQLExceptionDialog.openException(shell, bookmark, (SQLException) e.getCause());
        	} else {
	            ExceptionDisplayDialog.openError(shell, 
	                Messages.getString(getClass().getName() + ".title"), 
	                Messages.getString(getClass().getName() + ".message") +
					" (Bookmark:"+bookmark.getName()+")", e);
        	}
        }
        return connection;
    }

}