/*
 * Copyright (c) 2018-2028, AoKunSang All rights reserved.
 * 我问青山何时老，青山问我几时闲，
 * 不是闲人闲不得，能闲必非等闲人。
 */
package org.springblade.datasource.config;

import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.dynamic.datasource.creator.druid.DruidDataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import org.springblade.datasource.support.BladexDataSourceProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

/**
 * 启动配置类
 *
 * @author wookvn
 * @datetime 2025-01-13 17:35:58
 */
@Configuration
@ComponentScan("org.springblade.datasource")
@EnableConfigurationProperties(DynamicDataSourceProperties.class)
public class GmetryDatasourceAutoConfiguration {

    /**
     * 初始化动态数据源
     * @return
     */
    @Bean
    @ConditionalOnProperty(value = "blade.dynamic-db.enabled", havingValue = "true", matchIfMissing = false)
    public BladexDataSourceProvider bdsProvider(DefaultDataSourceCreator defaultDataSourceCreator, DynamicDataSourceProperties dynamicDataSourceProperties) {
        DataSourceProperty master = dynamicDataSourceProperties.getDatasource().get(dynamicDataSourceProperties.getPrimary());
        return new BladexDataSourceProvider(
                defaultDataSourceCreator,
                dynamicDataSourceProperties,
                master.getUrl(),
                master.getUsername(),
                master.getPassword());
    }

    /**
     * 动态数据源创建类
     * @param dataSourceCreator
     * @return
     */
    @Bean
    @ConditionalOnProperty(value = "blade.dynamic-db.enabled", havingValue = "true", matchIfMissing = false)
    public DefaultDataSourceCreator defaultDataSourceCreator(DruidDataSourceCreator dataSourceCreator) {
        DefaultDataSourceCreator defaultDataSourceCreator = new DefaultDataSourceCreator();
        defaultDataSourceCreator.setCreators(Arrays.asList(dataSourceCreator));
        return defaultDataSourceCreator;
    }
}
