package com.cf.imes.framework.mybatis.core.event;

import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.event.DataSourceInitEvent;
import com.cf.imes.framework.common.util.encrypt.AesUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.sql.DataSource;

/**
 * @author Gqr
 * @since 2024/8/27 9:09
 */
public class ChenfengDataSourceEncryptInitEvent implements DataSourceInitEvent {
    @Value("${chenfeng.encrypt.publicKey:}")
    private String publicKey;

    /**
     * 数据源创建前
     *
     * @param dataSourceProperty 数据源基础信息
     */
    @Override
    public void beforeCreate(DataSourceProperty dataSourceProperty) {
        if (StringUtils.isNotEmpty(publicKey)) {
            dataSourceProperty.setUsername(AesUtils.decrypt(dataSourceProperty.getUsername(), publicKey));
            dataSourceProperty.setPassword(AesUtils.decrypt(dataSourceProperty.getPassword(), publicKey));
        }
    }

    /**
     * 数据源创建后
     *
     * @param dataSource 连接池
     */
    @Override
    public void afterCreate(DataSource dataSource) {
        // nothing
    }
}
