package eu.dnetlib.sesame.xapool;

import java.sql.SQLException;

import javax.sql.XAConnection;
import javax.sql.XADataSource;

import org.enhydra.jdbc.standard.StandardXADataSource;
import org.openrdf.repository.Repository;
import org.openrdf.repository.RepositoryConnection;
import org.openrdf.repository.RepositoryException;
import org.springframework.beans.factory.annotation.Required;

/**
 * Implemented following org.enhydra.jdbc.oracle.OracleXADataSource example.
 * 
 * @author lexis
 */
public class XADataSourceSesame extends StandardXADataSource implements XADataSource {

	/**
	 * Default serial version.
	 */
	private static final long serialVersionUID = 1L;
	/** Sesame Repository instance already initialized. */
	private Repository repository;

	@Required
	public void setRepository(final Repository repository) {
		this.repository = repository;
	}

	public Repository getRepository() {
		return this.repository;
	}

	/** No args constructor. */
	public XADataSourceSesame() {
		super();
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.enhydra.jdbc.standard.StandardXADataSource#getXAConnection()
	 */
	@Override
	public XAConnection getXAConnection() throws SQLException {
		return this.getXAConnection(this.user, this.password);
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.enhydra.jdbc.standard.StandardXADataSource#getXAConnection(java.lang.String, java.lang.String)
	 */
	@Override
	public synchronized XAConnection getXAConnection(final String user, final String password) throws SQLException {
		//		 OracleXAConnection xac = new OracleXAConnection (this, user, password);
		//	        xac.setTransactionManager(transactionManager);
		//	        connectionCount++;
		//	        return xac;
		XAConnectionSesame xac = null;
		try {
			RepositoryConnection con = this.repository.getConnection();
			xac = new XAConnectionSesame(this, user, password, con);
			xac.setTransactionManager(this.transactionManager);
			//xac.setRepositoryCon(con);
			this.connectionCount++;
		} catch (RepositoryException e) {
			throw new SQLException("Cannot get connection from repository");
		}
		return xac;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.springframework.beans.factory.DisposableBean#destroy()
	 */
	public void destroy() throws Exception {
		this.log.debug("destroy()");
		super.shutdown(true);
		this.getPooledConnection().close();
	}

}
