package com.uas.platform.b2b.data.support;

import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Properties;
import java.util.logging.Logger;

import javax.sql.DataSource;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;

public class MultiDataSource extends DruidDataSource implements DataSource, ApplicationContextAware {

	private static final long serialVersionUID = 1L;

	private ApplicationContext applicationContext = null;
	private DruidDataSource dataSource = null;
	private Properties connectionProperties = null;

	@Override
    public DruidPooledConnection getConnection() throws SQLException {
		return getDataSource().getConnection();
	}

	@Override
    public Connection getConnection(String arg0, String arg1) throws SQLException {
		return getDataSource().getConnection(arg0, arg1);
	}

	@Override
    public PrintWriter getLogWriter() {
		return getDataSource().getLogWriter();
	}

	public Properties getConnectionProperties() {
		return connectionProperties;
	}

	public void setConnectionProperties(Properties connectionProperties) {
		this.connectionProperties = connectionProperties;
	}

	@Override
    public int getLoginTimeout() {
		return getDataSource().getLoginTimeout();
	}

	@Override
    public void setLogWriter(PrintWriter arg0) throws SQLException {
		getDataSource().setLogWriter(arg0);
	}

	@Override
    public void setLoginTimeout(int arg0) {
		getDataSource().setLoginTimeout(arg0);
	}

	@Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	public DruidDataSource getDataSource(String dataSourceName) {
		if (dataSourceName == null || dataSourceName.equals("")) {
			return this.dataSource;
		}
		return this.applicationContext.getBean(dataSourceName, DruidDataSource.class);
	}

	public void setDataSource(DruidDataSource dataSource) {
		this.dataSource = dataSource;
	}

	public DruidDataSource getDataSource() {
		String sp = SpObserver.getSp();
		return getDataSource(sp);
	}

	@Override
	public <T> T unwrap(Class<T> iface) {
		return null;
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) {
		return false;
	}

	@Override
	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		return null;
	}

}