package org.leonardo.ocean.db;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

import java.util.Arrays;

/**
 * Created by Leonardo - Ocean  on 2015/7/25.
 * Ψӫإ mongodb su
 */
public class ConnectionGenerator {

    protected int connectionMultiplier = 300;
    protected int connectionsPerHost = 10;
    protected int connectTimeout = 5000;
    protected int defaultPort = 27017;

    public ConnectionGenerator() {
       super();
    }



    //u{ݼƶq  * D̤jsu  = pool ƶq
    private MongoClientOptions options(){
        return new MongoClientOptions.Builder()
                .threadsAllowedToBlockForConnectionMultiplier(connectionMultiplier)	//u{ݪƶq
                .connectionsPerHost(connectionsPerHost)								//D̤jsu
                .connectTimeout(connectTimeout)
                .build();
    }

    protected MongoClient connection(String host){
        return connection(host, defaultPort);
    }

    protected MongoClient connection(String host, int port){
        MongoClient client = null;
        try{
            ServerAddress address = new ServerAddress(host, port);
            client = new MongoClient(address, options());
        }catch(Exception error) {
            if(client != null){
                client.close();
            }
            throw error;
        }
        return client;
    }

    /**ҫsuإ*/
    protected MongoClient connection(String host, int port , String dbName, String user, String password){
        MongoClient client = null;
        try {
            MongoCredential credential = MongoCredential.createMongoCRCredential(user, dbName, password.toCharArray());
            ServerAddress address = new ServerAddress(host, port);
            client = new MongoClient(address, Arrays.asList(credential), options());

        }catch (Exception error){
            if(client != null){
                client.close();
            }
            throw error;
        }
        return client;
    }
}

@@ -319,36 +319,25 @@
 ted int 
-connectionMultiplier
+waitCount
  = 300;%0A
@@ -350,25 +350,28 @@
 otected int 
-c
+maxC
 onnectionsPe
@@ -367,24 +367,16 @@
 nnection
-sPerHost
  = 10;%0A 
@@ -392,24 +392,17 @@
 ted int 
-connectT
+t
 imeout =
@@ -506,16 +506,230 @@
 %0A    %7D%0A%0A
+    public ConnectionGenerator(int waitCount, int maxConnection, int timeout) %7B%0A        super();%0A        this.waitCount = waitCount;%0A        this.maxConnection = maxConnection;%0A        this.timeout = timeout;%0A    %7D
 %0A%0A    //
@@ -910,30 +910,22 @@
 ier(
-connectionMultiplier)%09
+waitCount)    
 //u%7B
@@ -964,17 +964,20 @@
 PerHost(
-c
+maxC
 onnectio
@@ -981,25 +981,19 @@
 tion
-sPerHost
 )%09%09%09%09%09%09
-%09%09
+    
 //D%CC%A4
@@ -1028,24 +1028,17 @@
 Timeout(
-connectT
+t
 imeout)%0A

change property name.