package eu.dnetlib.sesame.xapool;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Driver implementation.
 * 
 * @author lexis
 */
public class DriverSesame implements Driver {

	/** Logger. */
	private static final Log log = LogFactory.getLog(DriverSesame.class);
	/** URL accepted by this driver starts with this String. */
	private static final String ACCEPTED_URL = "http://doroty-sesame/";

	static {
		try {
			DriverManager.registerDriver(new DriverSesame());
		} catch (SQLException e) {
			log.debug("Exception registering driver in static initializer (eu.dnetlib.sesame.xapool.DriverSesame) " + e);
		}
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see java.sql.Driver#acceptsURL(java.lang.String)
	 */
	public boolean acceptsURL(final String url) throws SQLException {
		return url.startsWith(DriverSesame.ACCEPTED_URL);
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see java.sql.Driver#connect(java.lang.String, java.util.Properties)
	 */
	public Connection connect(final String url, final Properties info) throws SQLException {
		/*
		 * I need the path to the datadir: it's in the url! http://doroty-sesame/pathToDir
		 */
		/*
		 * if (this.acceptsURL(url)) { String dataDir = url.replace(SesameDriver.ACCEPTED_URL, ""); File f = new
		 * File(dataDir); NativeStore nativeStore = new NativeStore(f); Repository rep = new
		 * SailRepository(nativeStore); SesameConnection sesameCon = new SesameConnection(); try { //If I call
		 * initialize the sail is already locked because it is a bean in the context //if I don't call it it says that
		 * the sail is not initialized... //TODO: How to pass an instance of repository to the driver?
		 * //rep.initialize(); sesameCon.setRepositoryConnection(rep.getConnection()); } catch (RepositoryException e) {
		 * throw new SQLException(e); } return sesameCon; } else return null;
		 */

		if (this.acceptsURL(url)) {
			return new ConnectionSesame();
		} else
			return null;

	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see java.sql.Driver#getMajorVersion()
	 */
	public int getMajorVersion() {
		return 1;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see java.sql.Driver#getMinorVersion()
	 */
	public int getMinorVersion() {
		return 0;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see java.sql.Driver#getPropertyInfo(java.lang.String, java.util.Properties)
	 */
	public DriverPropertyInfo[] getPropertyInfo(final String arg0, final Properties arg1) throws SQLException {
		return new DriverPropertyInfo[0];
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see java.sql.Driver#jdbcCompliant()
	 */
	public boolean jdbcCompliant() {
		return false;
	}

}
