import * as cassandra from 'cassandra-driver';
import * as Index from "./index.d";

export default class CustomCassandraConnectionPool {
  private options: Index.CustomCassandraOptions;
  public client: Index.ExtendedCassandraClient | null = null;

  constructor(options: Index.CassandraOptions, errorCallback: (err: any) => void, successCallback: () => void, callbackStatus: (err: any) => void) {
    this.options = options;

    if(this.options.user == undefined || this.options.password == undefined){
      errorCallback("User and password are required");
      return;   
    }

    let authProvider = new cassandra.auth.PlainTextAuthProvider(this.options.user, this.options.password);

    if(this.options.hosts == undefined || this.options.port == undefined){
      errorCallback("Host and port are required");
      return;   
    }

    let clientOptions: cassandra.ClientOptions = {
      contactPoints: this.options.hosts,
      keyspace: this.options.keyspace,
      authProvider: authProvider,
      protocolOptions: {
        port: this.options.port,
        maxSchemaAgreementWaitSeconds: 10,
        maxVersion: 0 //Default values can be find in "cassandra-driver/lib/client-options.js:52"
      }
    }
    this.client = <Index.ExtendedCassandraClient>new cassandra.Client(clientOptions);

    this.client.controlConnection.on('newConnection', function (err: any, connection: any, host: any) {
      callbackStatus(err);
    });


    this.client.connect(function (err: any) {
      if (err)
        errorCallback(err);
      else
        successCallback();
    });
  }
}