/*
** Module dependencies
*/
var request = require('superagent');
require('superagent-retry')(request);
var Agent = require('http').Agent;
var _ = require('lodash');
var libxml = require('libxmljs');
var namespaces = require('./namespaces');
var harvest = require('./harvest');


/*
** Constructor
*/
function Client(url, options) {
    if (!url) throw new Error('URL is required!');
    this.url = url;
    this.options = options || {};

    if (this.options.maxSockets) {
        this.agent = new Agent();
        this.agent.maxSockets = this.options.maxSockets;
    }
}

/*
** Private methods
*/
Client.prototype.request = function(query, cb) {
    var req = request
        .get(this.url)
        .set('user-agent', 'Node-CSW' || this.options.userAgent)
        .query({ service: 'CSW', version: '2.0.2' })
        .query(query);

    if (this.agent) req.agent(this.agent);
    if (this.options.retry) req.retry(this.options.retry);

    req.buffer()
        .end(function(err, res) {
            if (err) return cb(err);
            if (!res.text || !res.text.length) return cb(new Error('Empty body'));

            var xmlDoc;
            try {
                xmlDoc = libxml.parseXml(res.text, { noblanks: true });
                cb(null, xmlDoc);
            } catch(e) {
                console.log(res.req.path);
                console.log(e);
                cb(e);
            }
        });

    return req;
};

Client.prototype.mapOptions = function(options) {
    var query = {};
    // Mapping original params
    _.extend(query, _.pick(options, 'maxRecords', 'startPosition', 'typeNames', 'outputSchema', 'elementSetName', 'resultType'));
    if (options.limit) query.maxRecords = options.limit;
    if (options.offset) query.startPosition = options.offset + 1;
    return query;
};

/*
** Public methods
*/
Client.prototype.getRecordById = function(id, options, cb) {
    if (!cb) {
        cb = options;
        options = {};
    }

    if (_.isArray(id)) {
        id = id.join(',');
    }

    options = this.mapOptions(options);
    options.request = 'GetRecordById';
    options.id = id;

    this.request(options, cb);
};

Client.prototype.getRecords = function(options, cb) {
    if (!cb) {
        cb = options;
        options = {};
    }

    options = this.mapOptions(options);

    _.defaults(options, {
        constraintLanguage: 'CQL_TEXT',
        resultType: 'results',
        maxRecords: 10,
        typeNames: 'csw:Record'
    });

    options.request = 'GetRecords';

    this.request(options, cb);
};

Client.prototype.getCapabilities = function(cb) {
    this.request({ request: 'GetCapabilities' }, cb);
};

Client.prototype.numRecords = function(options, cb) {
    if (!cb) {
        cb = options;
        options = {};
    }

    options = this.mapOptions(options);
    options.resultType = 'hits';

    this.getRecords(options, function(err, xmlDoc) {
        if (err) return cb(err);
        var numberOfRecordsMatched = xmlDoc.get('//csw:SearchResults/@numberOfRecordsMatched', namespaces);
        if (numberOfRecordsMatched) cb(null, parseInt(numberOfRecordsMatched.value()));
        else {
            cb(new Error('Unable to find numberOfRecordsMatched attribute'));
        }
    });
};

Client.prototype.harvest = function(options) {
    return harvest(this, options);
};


/*
** Exports
*/
module.exports = Client;

@@ -22,16 +22,134 @@
 cies%0A*/%0A
+var HttpAgent = require('http').Agent;%0Avar HttpsAgent = require('https').Agent;%0Avar parseUrl = require('url').parse;%0A%0A
 var requ
@@ -177,16 +177,16 @@
 gent');%0A
-
 require(
@@ -219,43 +219,8 @@
 t);%0A
-var Agent = require('http').Agent;%0A
 var 
@@ -272,24 +272,25 @@
 libxmljs');%0A
+%0A
 var namespac
@@ -353,24 +353,103 @@
 arvest');%0A%0A%0A
+/*%0A** Config%0A*/%0Avar Agent = %7B%0A  'http:': HttpAgent,%0A  'https:': HttpsAgent%0A%7D;%0A%0A
 /*%0A** Constr
@@ -626,16 +626,42 @@
 xSockets
+ %7C%7C this.options.keepAlive
 ) %7B%0A    
@@ -690,57 +690,68 @@
 gent
-();%0A        this.agent.maxSockets = this.options.
+%5BparseUrl(url).protocol%5D(_.pick(this.options, 'keepAlive', '
 maxS
@@ -756,16 +756,19 @@
 xSockets
+'))
 ;%0A    %7D%0A
@@ -893,73 +893,8 @@
 rl)%0A
-        .set('user-agent', 'Node-CSW' %7C%7C this.options.userAgent)%0A
     
@@ -962,24 +962,24 @@
 ry(query);%0A%0A
-
     if (this
@@ -1008,16 +1008,136 @@
 .agent);
+ // Must be called before any set method!%0A    if (this.options.userAgent) req.set('User-Agent', this.options.userAgent);
 %0A    if 

Fix issue with HTTPS