package org.bdware.sc.boundry.utils;

import org.bdware.sc.compiler.PermissionStub;
import org.bdware.sc.node.Permission;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

@PermissionStub(permission = Permission.MongoDB)
public class MongoDBUtil {
    public static Object connect(String url, int port, String dbName, String usrName, String pwd) {
        try {
            Class serverAddr = Class.forName("com.mongodb.ServerAddress");
            Constructor cons = serverAddr.getConstructor(String.class, Integer.TYPE);
            Object serverAddress = cons.newInstance(url, port);
            List addrs = new ArrayList<>();
            addrs.add(serverAddress);
            Method createeScramSha1 =
                    Class.forName("com.mongodb.MongoCredential")
                            .getDeclaredMethod(
                                    "createScramSha1Credential",
                                    String.class,
                                    String.class,
                                    char[].class);
            Object credential = createeScramSha1.invoke(null, usrName, dbName, pwd.toCharArray());
            List credentials = new ArrayList<>();
            credentials.add(credential);
            Constructor mongoClient =
                    Class.forName("com.mongodb.MongoClient").getConstructor(List.class, List.class);
            Object client = mongoClient.newInstance(addrs, credentials);
            // 通过连接认证获取MongoDB连接
            return client;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
