package com.atomikos.examples.opentracing;

import javax.jms.ConnectionFactory;
import javax.sql.DataSource;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.jta.atomikos.AtomikosConnectionFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import com.atomikos.opentracing.jdbc.OpenTracingDataSourceBean;
import com.atomikos.opentracing.jms.OpenTracingConnectionFactoryBean;

import io.opentracing.Tracer;

@Configuration
public class OpenTracingConfiguration {
    

    public OpenTracingConfiguration(Tracer opentracingTracer) {
        io.opentracing.util.GlobalTracer.registerIfAbsent(opentracingTracer);
    }
    
    
    
    @Bean
    public BeanPostProcessor openTracingDataSourcePostProcessor() {
        return new BeanPostProcessor() {
        	@Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (bean instanceof AtomikosDataSourceBean) {
                    return new OpenTracingDataSourceBean((DataSource) bean);
                }
                if (bean instanceof AtomikosConnectionFactoryBean) {
                	return new OpenTracingConnectionFactoryBean((ConnectionFactory)bean);
                }
                return bean;
            }
        };
    }
    
}
