package com.yonge.toolset.datasource.service.impl;

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

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.alibaba.druid.pool.DruidDataSource;
import com.yonge.toolset.datasource.DynamicRoutingDataSource;
import com.yonge.toolset.datasource.dao.DatabaseSourceDao;
import com.yonge.toolset.datasource.entity.DatabaseSource;
import com.yonge.toolset.datasource.service.DatabaseSourceService;

@Service
public class DatabaseSourceServiceImpl implements DatabaseSourceService, ApplicationContextAware,
		InitializingBean {
	
	private final static String DEFAULT_DATA_SOURCE_KEY = "master";

	@Autowired
	private DatabaseSourceDao databaseSourceDao;

	private ApplicationContext applicationContext;

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

	@Override
	public void afterPropertiesSet() throws Exception {

		DynamicRoutingDataSource dynamicDataSource = (DynamicRoutingDataSource) applicationContext.getBean("dynamicDataSource");
		DruidDataSource master = (DruidDataSource) applicationContext.getBean(DEFAULT_DATA_SOURCE_KEY);
		Map<Object, Object> dataSourceMap = new HashMap<>();
		dataSourceMap.put("master", master);

		List<DatabaseSource> dbSourceList = databaseSourceDao.findAll(null);
		for (DatabaseSource ds : dbSourceList) {
			DruidDataSource dataSource = new DruidDataSource();

			dataSource.setDriverClassName(ds.getDriver());
			dataSource.setUrl(ds.getUrl());
			dataSource.setUsername(ds.getUsername());
			dataSource.setPassword(ds.getPassword());
			dataSource.setConnectProperties(master.getConnectProperties());

			dataSourceMap.put(ds.getTenantId(), dataSource);
		}

		dynamicDataSource.setTargetDataSources(dataSourceMap);

		// 必须执行此操作，才会重新初始化AbstractRoutingDataSource 中的 resolvedDataSources，也只有这样，动态切换才会起效
		dynamicDataSource.afterPropertiesSet();
	}

}
