'use strict';

const Connection = require('../../../lib/core/cmap/connection');
const connect = require('../../../lib/core/connection/connect');
const expect = require('chai').expect;
const BSON = require('bson');

describe('Connection', function() {
  it('should execute a command against a server', function(done) {
    const connectOptions = Object.assign(
      { connectionType: Connection, bson: new BSON() },
      this.configuration.options
    );

    connect(connectOptions, (err, conn) => {
      expect(err).to.not.exist;

      conn.command('admin.$cmd', { ismaster: 1 }, (err, ismaster) => {
        expect(err).to.not.exist;
        expect(ismaster).to.exist;
        expect(ismaster.ok).to.equal(1);

        conn.destroy(done);
      });
    });
  });

  it('should emit command monitoring events', function(done) {
    const connectOptions = Object.assign(
      { connectionType: Connection, bson: new BSON(), monitorCommands: true },
      this.configuration.options
    );

    connect(connectOptions, (err, conn) => {
      expect(err).to.not.exist;

      const events = [];
      conn.on('commandStarted', event => events.push(event));
      conn.on('commandSucceeded', event => events.push(event));
      conn.on('commandFailed', event => events.push(event));

      conn.command('admin.$cmd', { ismaster: 1 }, (err, ismaster) => {
        expect(err).to.not.exist;
        expect(ismaster).to.exist;
        expect(ismaster.ok).to.equal(1);

        expect(events).to.have.length(2);
        console.dir({ events }, { depth: 3 });

        conn.destroy(done);
      });
    });
  });
});

@@ -518,32 +518,80 @@
 r).to.not.exist;
+%0A      this.defer(_done =%3E conn.destroy(_done));
 %0A%0A      conn.com
@@ -757,25 +757,24 @@
 ual(1);%0A
-%0A
         
 conn.des
@@ -765,33 +765,21 @@
         
-c
+d
 on
-n.destroy(don
 e
+(
 );%0A     
@@ -1099,16 +1099,64 @@
 t.exist;
+%0A      this.defer(_done =%3E conn.destroy(_done));
 %0A%0A      
@@ -1543,17 +1543,16 @@
 ual(1);%0A
-%0A
         
@@ -1597,73 +1597,13 @@
     
-console.dir(%7B events %7D, %7B depth: 3 %7D);%0A%0A        conn.destroy(
 done
+(
 );%0A 

use `defer` to ensure connections are closed in all cases