var core = require('../index.js');
var Clients = core.Client;

var CollapsedClient = function (klass, cp) {
    this._client = new Clients[klass](cp);
    this._cf_queries = {};
};


CollapsedClient.prototype.get = function (key, opts, callback) {
    var that = this;
    var cf_key = 'get_' + key;
    
    if (this._cf_queries.hasOwnProperty(cf_key)) {
        this._cf_queries[cf_key].push(callback);
        return;
    }

    this._cf_queries[cf_key] = [callback];

    this._client.get(key, opts, function (err, data) {
        that._spawnCallbacks(cf_key, err, data);
    });
};

CollapsedClient.prototype.set = function (key, opts, callback) {
    this._client.set(key, opts, callback);
};

CollapsedClient.prototype['delete'] = function (key, opts, callback) {
    this._client['delete'](key, opts, callback);
};

CollapsedClient.prototype._spawnCallbacks = function (cf_key, err, data) {
    var callback;

    while (callback = this._cf_queries[cf_key].shift()) {
        callback(err, data);
    }
    delete this._cf_queries[cf_key];
};

exports.CollapsedClient = CollapsedClient;
