### ----------------------------------------------------
### -- MongoDB
### -- Licenses: Artistic-2.0
### -- Authors: Marcel Timmerman, Paweł Pabian
### -- File: xt/Tests/Basic/150-SocketPool.rakutest
### ----------------------------------------------------
use Test;

use BSON::Document;

use MongoDB;
use MongoDB::Client;
use MongoDB::Database;
use MongoDB::SocketPool::Socket;
use MongoDB::SocketPool;

#-------------------------------------------------------------------------------
my Str $log-path = @*ARGS[0];
my Version $version .= new(@*ARGS[1]);
my @server-ports = @*ARGS[2..*];
#note "args: $log-path, $version, @server-ports";

#-------------------------------------------------------------------------------
drop-send-to('mongodb');
drop-send-to('screen');
#modify-send-to( 'screen', :level(MongoDB::MdbLoglevels::Trace));
my $handle = $log-path.IO.open( :mode<wo>, :append);
add-send-to( 'mdb', :to($handle), :min-level(MongoDB::MdbLoglevels::Debug));
#set-filter(|<ObserverEmitter Timer Socket>);

info-message("Test $?FILE start");

#-------------------------------------------------------------------------------
my Str $uri = "mongodb://localhost:@server-ports[0]";
my MongoDB::Client $client .= new(:$uri);
my $uri-obj = $client.uri-obj;
my Str $host = $uri-obj.servers[0]<host>;
my Int $port = $uri-obj.servers[0]<port>.Int;

my MongoDB::SocketPool $sockets;

#-------------------------------------------------------------------------------
subtest "SocketPool creation", {
  dies-ok( { $sockets .= new; }, '.new() not allowed');

  $sockets .= instance;
  isa-ok $sockets, MongoDB::SocketPool;
}

#-------------------------------------------------------------------------------
subtest "SocketPool manipulations", {

  # Must use the connection to have a socket in the pool
  my MongoDB::Database $database = $client.database('mt-test');
  my BSON::Document $doc = $database.run-command: (getLastError => 1,);
  is $doc<ok>, 1, 'No last errors';

  # get a socket without uri object -> mimic Monitor
  my MongoDB::SocketPool::Socket $s = $sockets.get-socket(
    $host, $port, :uri-obj($client.uri-obj)
  );

  isa-ok $s, MongoDB::SocketPool::Socket;

  # cleanup Monitor sockets
  #ok $sockets.cleanup( '__MONITOR__CLIENT_KEY__', "host:$port"), '.cleanup()';
  #ok $sockets.cleanup( $client.uri-obj.client-key, "$host:$port"), '.cleanup()';
}

#-------------------------------------------------------------------------------
info-message("Test $?FILE stop");
done-testing();


