package com.usoftchina.bi.test.server;

import com.usoftchina.bi.core.jdbc.DynamicDataSource;
import com.usoftchina.bi.core.jdbc.DynamicDataSourceContextHolder;
import com.usoftchina.bi.core.jdbc.DynamicDataSourceRegister;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Import;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


@RunWith(SpringRunner.class)
@SpringBootTest
@Import({DynamicDataSourceRegister.class})
@EnableAutoConfiguration
public class TestDataSource{

	@Autowired
	private ApplicationContext app;
	@Autowired
	private DynamicDataSourceRegister dataSourceRegister;
	@Autowired
	private JdbcTemplate JdbcTemplate;

	private static final Logger logger = LoggerFactory.getLogger(TestDataSource.class);

	@Test
	public void test(){
        logger.info("begin==========================");
		addDataSource();
        logger.info("end============================");
	}
	
	private void testQuery(){
		DynamicDataSourceContextHolder.setDataSourceType("UAS");
		List<Map<String, Object>> list = JdbcTemplate.queryForList("SELECT EN_NAME FROM ENTERPRISE");
		logger.info("UAS:{}", list);
		DynamicDataSourceContextHolder.setDataSourceType("UAS_DEV");
		List<Map<String, Object>> list2 = JdbcTemplate.queryForList("SELECT EN_NAME FROM ENTERPRISE");
		logger.info("UAS_DEV:{}", list2);
		DynamicDataSourceContextHolder.setDataSourceType("UAS_TEST");
		List<Map<String, Object>> list3 = JdbcTemplate.queryForList("SELECT EN_NAME FROM ENTERPRISE");
		logger.info("UAS_TEST:{}", list3);
	}
	
	private void addDataSource(){
		
		//额外的数据源
		Map<String, Object> dsMap = new HashMap<>();
        dsMap.put("driver", "oracle.jdbc.driver.OracleDriver");
        dsMap.put("url", "jdbc:oracle:thin:@10.1.81.2:1521:orcl");
        dsMap.put("username", "UAS_TEST");
        dsMap.put("password", "select!#%*(");
        Map<Object, Object> target = dataSourceRegister.getTargetDataSources();
        if(target.size() == 0){
        	target.putAll(dataSourceRegister.getSlaveDataSources());
        }
        target.put("UAS_TEST", dataSourceRegister.buildDataSource(dsMap));
        DynamicDataSource datasource=(DynamicDataSource)app.getBean("dataSource");
        datasource.setTargetDataSources(target);
        datasource.afterPropertiesSet();

        Set<Object> dataSourceIds = DynamicDataSourceContextHolder.getDataSourceIds();
        dataSourceIds.add("UAS_TEST");
        DynamicDataSourceContextHolder.setDataSourceIds(dataSourceIds);

		testQuery();
	}

}
