var Class = require('../class/Class.js').Class;
var Memcache = require('./Memcache.js').Memcache;
var assertions = require('../common/Assertions.js');

var CFMemcache = function(){
    this.Extends = Memcache;
    
    /*
    this._memory = {};
    */

    this.initialize = function(options){
        this.parent(options);
        this._memory = {};
    };
    
    this.get = function(key, callback){
        assertions.isString(key, Memcache.Exception.WRONG_TYPE);
        
        if(this._memory.hasOwnProperty(key)){
             this._memory[key].callbacks.push(callback);
        } else {
            // dodaje klucz do memory
            this._memory[key] = {
                data: null,
                callbacks: [callback]
            };
            var that = this;
            this.parent(key, function(data){
                that._memory[key].data = data;
                for(var cbIndex=0,max=that._memory[key].callbacks.length;cbIndex<max;cbIndex++){
                    try{
                        that._memory[key].callbacks[cbIndex](that._memory[key].data);
                    } catch (ex){
                        console.error('emerg', ex.message);
                    }
                }
                delete that._memory[key];
            });
        }
    };
    
    this.set = function(key, value, callback, lifeTime, waitForReply){
        assertions.isString(key, Memcache.Exception.WRONG_TYPE);
        if(this._memory.hasOwnProperty(key)){
            this._memory[key].data = value;
        }
        this.parent(key, value, callback, lifeTime, waitForReply);
    };
    
    this['delete'] = function(key, callback){
        assertions.isString(key, Memcache.Exception.WRONG_TYPE);
        if(this._memory.hasOwnProperty(key)){
            this._memory[key].data = null;
        }
        this.parent(key, callback);
    };

};
CFMemcache = new Class(new CFMemcache());
exports.CFMemcache = CFMemcache;
