package jp.sf.amateras.mirage.session;

import java.sql.Connection;
import java.sql.DriverManager;

import jp.sf.amateras.mirage.SqlManager;
import jp.sf.amateras.mirage.SqlManagerImpl;
import jp.sf.amateras.mirage.exception.SessionException;
import jp.sf.amateras.mirage.provider.DefaultConnectionProvider;

/**
 * The default inplementation of {@link Session}.
 *
 * @author Naoki Takezoe
 */
public class JDBCSessionImpl implements Session {

	private SqlManager sqlManager;
	private DefaultConnectionProvider provider;
	private String driver;
	private String url;
	private String user;
	private String password;

	public JDBCSessionImpl(String driver, String url, String user, String password){
		this.driver = driver;
		this.url = url;
		this.user = user;
		this.password = password;

		sqlManager = new SqlManagerImpl();
		provider = new DefaultConnectionProvider();
		sqlManager.setConnectionProvider(provider);
	}

//	@Override
	public void begin() throws SessionException {
		try {
			Class.forName(driver);
			Connection conn = DriverManager.getConnection(url, user, password);
			conn.setAutoCommit(false);
			provider.setConnection(conn);
		} catch(Exception ex){
			throw new SessionException("Failed to begin transaction.", ex);
		}
	}

//	@Override
	public void commit() throws SessionException {
		try {
			provider.getConnection().commit();
		} catch(Exception ex){
			throw new SessionException("Failed to commit transaction.", ex);
		}
	}

//	@Override
	public SqlManager getSqlManager() throws SessionException {
		return sqlManager;
	}

//	@Override
	public void release() throws SessionException {
		if(provider instanceof DefaultConnectionProvider){
			((DefaultConnectionProvider) provider).releaseConnection();
		}
	}

//	@Override
	public void rollback() throws SessionException {
		try {
			provider.getConnection().rollback();
		} catch(Exception ex){
			throw new SessionException("Failed to rollback transaction.", ex);
		}
	}

}
