package org.gcube.application.geoportal.service.model.internal.db;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.gcube.application.geoportal.common.model.configuration.MongoConnection;

@Slf4j
@ToString
public class Mongo {
    @Getter
    private MongoClient theClient = null;
    @Getter
    private MongoConnection connection = null;

    public Mongo(MongoConnection conn) {
        connection = conn;
        MongoCredential credential = MongoCredential.createCredential(conn.getUser(), conn.getDatabase(),
                conn.getPassword().toCharArray());

        MongoClientOptions options = MongoClientOptions.builder().
                threadsAllowedToBlockForConnectionMultiplier(10).
                connectionsPerHost(20).
                maxConnectionIdleTime(10000).
                applicationName("geoportal-service").
                sslEnabled(true).
                connectTimeout(30000).
                build();

        theClient = new MongoClient(new ServerAddress(conn.getHosts().get(0), conn.getPort()),
                credential,
                options);
    }

    public void close() {
        theClient.close();
    }
}
