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

/**
 * Objects to be used as an operands of @Sql.Filter. It represents a two
 * expressions basic operation composed by a table column, the operator and the
 * value extracted from the rendering paramerers.
 */
module.exports = new Class
({
	Extends: Operation
	,Tag: 'sql-filter-item'
	,Properties:
	{
		/**
		 * The column name.
		 */
		field:
		{
			type: String,
			value: null
		},
		/**
		 * The source table name or its alias if it has been specified.
		 */
		target:
		{
			type: String,
			value: null
		},
		/**
		 * The parameter name.
		 */
		param:
		{
			type: String,
			value: null
		}
	}

	/**
	 * Checks if parameter name haa been defined and if it has a value.
	 */
	,isReady: function (params)
	{
		return this.param != null && params != null && params[this.param] != null;
	}

	,render: function (params)
	{
		var op = new Operation ({type: this.type});

		var field = new Field ({
			name: this.field,
			target: this.target
		});
		op.appendChild (field);

		var value = params[this.param];

		if (this.type === Operation.Type.LIKE && typeof value == 'string')
		{
			value = value.replace (/[\%\?]/g, this._escapeChar);
			value = value.replace (/^|\s+|$/g, '%');
		}

		var sqlValue = new Value ({value: value});
		op.appendChild (sqlValue);
			
		return op.render (params);
	}

	,_escapeChar: function (char)
	{
		return '\\'+ char;
	}
});