Ext.namespace("Ext.ux.data");

/**
 * Store Extension Class
 *
 * @author jjvegter
 * @version 1.0
 *
 * @class Ext.ux.data.CachingStore
 * @extends Ext.data.Store
 * @constructor
 * @param
 */

Ext.ux.data.CachingStore = Ext.extend(Ext.data.Store, {
	constructor : function(config) {
		this.lastQuery = 'bar';

        // constructor pre-processing - configure listeners here
        config = config || {};

		Ext.ux.data.CachingStore.superclass.constructor.apply(this, arguments);
	},

    /**
     * Executes a CRUD action on a proxy if a Writer is set.  Should not be used directly.  Called automatically
     * by Store#add, Store#remove, Store#afterEdit
     * @param {String} action
     * @param {Record/Record[]} rs
     * @param {Object} options
     * @throws Error
     * @private
     */
    execute : function(action, rs, options) {
        // blow up if action not Ext.data.CREATE, READ, UPDATE, DESTROY
        if (!Ext.data.Api.isAction(action)) {
            throw new Ext.data.Api.Error('execute', action);
        }
        // make sure options has a params key
        options = Ext.applyIf(options||{}, {
            params: {}
        });

        // have to separate before-events since load has a different signature than create,destroy and save events since load does not
        // include the rs (record resultset) parameter.  Capture return values from the beforeaction into doRequest flag.
        var doRequest = true;

        if (action === "read") {
            doRequest = this.fireEvent('beforeload', this, options);
        }
        else {
            // if Writer is configured as listful, force single-recoord rs to be [{}} instead of {}
            if (this.writer.listful === true && this.restful !== true) {
                rs = (Ext.isArray(rs)) ? rs : [rs];
            }
            // if rs has just a single record, shift it off so that Writer writes data as "{}" rather than "[{}]"
            else if (Ext.isArray(rs) && rs.length == 1) {
                rs = rs.shift();
            }
            // Write the action to options.params
            if ((doRequest = this.fireEvent('beforewrite', this, action, rs, options)) !== false) {
                this.writer.write(action, options.params, rs);
            }
        }
        if (doRequest !== false) {
            //var params = Ext.apply(options.params || {}, this.baseParams);
            var params = Ext.apply({}, options.params, this.baseParams);
            if (this.writer && this.proxy.url && !this.proxy.restful && !Ext.data.Api.hasUniqueUrl(this.proxy, action)) {
                params.xaction = action;
            }

            // custom stuff to filter if necessary
			if (action === "read" && this.isFilterLocal(params)) {
				(function() {
                    if (this.allData) {
                        this.data = this.allData;
                        delete this.allData;
                    }
                    this.applyFilterLocal(params);
                    this.fireEvent("datachanged", this);
                    var r = [].concat(this.data.items);
                    this.fireEvent("load", this, r, options);
                    if (options.callback) {
                        options.callback.call(options.scope || this, r, options, true);
                    }
                }).defer(1, this);
				return true;
			}

            // Note:  Up until this point we've been dealing with "action" as a key from Ext.data.Api.actions.  We'll flip it now
            // and send the value into DataProxy#request, since it's the value which maps to the DataProxy#api
            this.proxy.request(Ext.data.Api.actions[action], rs, params, this.reader, this.createCallback(action, rs), this, options);
        }
        return doRequest;
    },

    isFilterLocal: function(params) {
    	var r = this.getAt(0);

    	if(r && r.json.identificatie === 'planTooMuch') {
    		return false;
    	}

		if(this.lastQuery.length > 0 && params.query.substring(0, this.lastQuery.length) == this.lastQuery) {
			return true;
		}
		else {
			this.clearFilter();
			this.lastQuery = params.query || 'foo';
	    	return false;
		}
    },
    applyFilterLocal: function(params) {
		this.filter('name', params.query, false, false);
    },

	reset : function() {
		//this.clearFilter();
		this.lastQuery = '';
		this.removeAll();
	}
});
