package com.bonus.file.mongodb.config;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @author coisini
 * @version 1.0
 * @Description MongoDB配置类
 * @date Apr 17, 2022
 */
@Configuration
public class MongoConfig {
    /**
     * 数据库配置信息
     */
    @Value("${spring.data.mongodb.database}")
    private String db;

    @Value("${spring.data.mongodb.host}")
    private String host;

    @Value("${spring.data.mongodb.port}")
    private Integer port;

    private static final String UN = "zhgd";

    private static final String PD = "Bonus%40admin123";

    private MongoDatabase mongoDatabase;

    public MongoClient getMongoClient() {
        String addr = "mongodb://" + UN + ":" + PD + "@" + host + ":" + port + "/" + db;
        MongoClient mongoClient = MongoClients.create(addr);
        return mongoClient;
    }

    public MongoDatabase getMongoConn() {
        MongoClient mongoClient = getMongoClient();
        mongoDatabase = mongoClient.getDatabase(db);
        System.out.println("mongodb数据库连接成功！");
        return mongoDatabase;
    }

    @Bean
    public GridFSBucket getGridFsBucket() {
        MongoDatabase mongoDatabase = getMongoConn();
        return GridFSBuckets.create(mongoDatabase);
    }
}
