
var Operation = require ('./operation');
var Value = require ('./value');

/**
 * The equivalent of a SQL filter expression. It allows to automatically build
 * SQL filters based on lot parameters.
 */
module.exports = new Class
({
	Extends: Operation
	,Tag: 'sql-filter'

	/**
	 * Checks if any of filters childs are ready.
	 */
	,isReady: function (params)
	{
		var exprs = this.exprs.objects;
		for (var i = exprs.length; i--;)
		if (exprs[i].isReady (params))
			return true;

		return false;
	}

	/**
	 * Renders the filter as an SQL expression. If any of its childs isn't
	 * ready is ommitted from the expression. If all of its childs aren't ready
	 * renders the TRUE expression.
	 */
	,render: function (params)
	{
		var op = new Operation ({type: this.type});
		var exprs = this.exprs.objects;

		for (var i = 0; i < exprs.length; i++)
		if (exprs[i].isReady (params))
			op.exprs.add (exprs[i]);
	
		if (op.exprs.objects.length == 0)
			op = new Value ({value: true});
			
		return op.render (params);
	}
});
