package common.db.dao.hibernate;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.Objects;

import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.UnknownUnwrapTypeException;
import org.hibernate.service.spi.Configurable;
import org.hibernate.service.spi.Stoppable;

import common.db.JdbcSource;

import core.config.Factory;

/**
 * コネクション提供クラス
 * @author Tadashi Nakayama
 */
public final class DaoConnectionProvider implements ConnectionProvider, Configurable, Stoppable {

	/** serialVersionUID */
	private static final long serialVersionUID = 8713643751496912972L;

	/** 接続名 */
	private String name;

	/**
	 * @see org.hibernate.service.spi.Configurable#configure(java.util.Map)
	 */
	@Override
	public void configure(final Map configurationValues) {
		this.name = Objects.toString(configurationValues.get("resource_name"), null);
	}

	/**
	 * @see org.hibernate.engine.jdbc.connections.spi.ConnectionProvider
	 * #closeConnection(java.sql.Connection)
	 */
	@Override
	public void closeConnection(final Connection arg0) throws SQLException {
		arg0.close();
	}

	/**
	 * @see org.hibernate.engine.jdbc.connections.spi.ConnectionProvider#getConnection()
	 */
	@Override
	public Connection getConnection() throws SQLException {
		return JdbcSource.getConnection(this.name);
	}

	/**
	 * @see org.hibernate.engine.jdbc.connections.spi.ConnectionProvider
	 * #supportsAggressiveRelease()
	 */
	@Override
	public boolean supportsAggressiveRelease() {
		return false;
	}

	/**
	 * @see org.hibernate.service.spi.Wrapped#isUnwrappableAs(java.lang.Class)
	 */
	@Override
	public boolean isUnwrappableAs(final Class unwrapType) {
		return ConnectionProvider.class.equals(unwrapType)
				|| DaoConnectionProvider.class.isAssignableFrom(unwrapType);
	}

	/**
	 * @see org.hibernate.service.spi.Wrapped#unwrap(java.lang.Class)
	 */
	@Override
	public <T> T unwrap(final Class<T> unwrapType) {
		if (isUnwrappableAs(unwrapType)) {
			return Factory.cast(this);
		}
		throw new UnknownUnwrapTypeException(unwrapType);
	}

	/**
	 * @see org.hibernate.service.spi.Stoppable#stop()
	 */
	@Override
	public void stop() {
		return;
	}
}
