/**
 * 
 */
package org.springblade.datasource.support;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.druid.DruidDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import lombok.extern.slf4j.Slf4j;
import org.springblade.datasource.model.DatasourceDto;
import org.springblade.datasource.util.DatasourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author wookvn
 *
 */
@Slf4j
@Component
public class DynamicDataSourceSupport {

	@Autowired
	private DynamicRoutingDataSource dynamicRoutingDataSource;

	@Autowired
	private DruidDataSourceCreator dataSourceCreator;
	
	@Autowired
	private DynamicDataSourceProperties dynamicDataSourceProperties;

	/**
	 * 添加数据源
	 * 
	 * @param ds
	 * @return
	 */
	public boolean addDs(DatasourceDto ds) {
		try {
			if (DatasourceUtil.testDs(ds) == null) {
				DataSourceProperty dataSourceProperty = new DataSourceProperty();
				dataSourceProperty.setPoolName(ds.getPoolName());
				dataSourceProperty.setUrl(ds.getUrl());
				dataSourceProperty.setUsername(ds.getDsUser());
				dataSourceProperty.setPassword(ds.getDsPassword());
				dataSourceProperty.setDriverClassName(ds.getDriverClassName());
				//设置数据源连接属性
				dataSourceProperty.setDruid(DatasourceUtil.customConnectionConfig(dynamicDataSourceProperties.getDruid(), ds));
				DataSource dataSource = dataSourceCreator.createDataSource(dataSourceProperty);
				dynamicRoutingDataSource.addDataSource(ds.getPoolName(), dataSource);
				return true;
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw new RuntimeException("数据源连接失败");
		}
		return false;
	}

	/**
	 * 移除数据源
	 * 
	 * @param poolName
	 * @return
	 */
	public boolean removeDs(String poolName) throws Exception {
		dynamicRoutingDataSource.removeDataSource(poolName);
		return true;
	}

	/**
	 * 获取所有数据源
	 * 
	 * @return List<poolName>
	 */
	public List<String> getAllDs() {
		List<String> dsList = new ArrayList<String>();
		Map<String, DataSource> dataSources = dynamicRoutingDataSource.getDataSources();
		if (dataSources != null && !dataSources.isEmpty()) {
			for (Map.Entry<String, DataSource> entry : dataSources.entrySet()) {
				dsList.add(entry.getKey());
			}
		}
		return dsList;
	}


}
