
var Expr = require ('./expr');

/**
 * The equivalent of a SQL value.
 */
module.exports = new Class
({
	Extends: Expr
	,Implements: Vn.ParamIface
	,Tag: 'sql-value'
	,Properties:
	{
		value:
		{
			type: null
			,set: function (x)
			{
				this._setValue (x);
			}
			,get: function ()
			{
				return this._value;
			}
		},
		type:
		{
			type: Type
			,set: function (x)
			{
				this._setType (x);
			}
			,get: function ()
			{
				return this._type;
			}
		},
		param:
		{
			type: Vn.ParamIface
			,set: function (x)
			{
				this._setParam (x);
			}
			,get: function ()
			{
				return this._param;
			}
		},
		lot:
		{
			type: Vn.LotIface
			,set: function (x)
			{
				this._setLot (x);
			}
			,get: function ()
			{
				return this._lot;
			}
		},
		name:
		{
			type: String
			,set: function (x)
			{
				this._name = x;
				this._onLotChange ();
			}
			,get: function ()
			{
				return this._name;
			}
		},
		oneWay:
		{
			type: Boolean
			,set: function (x)
			{
				this._oneWay = x;
			}
			,get: function ()
			{
				return this._oneWay;
			}
		}
	}

	,regexp: new RegExp ('(\\\\)|\'', 'g')
	
	,isReady: function ()
	{
		return this._value !== undefined;
	}
	
	,replaceFunc: function (token)
	{
		switch (token)
		{
			case '\\': return '\\\\';
			case '\'': return '\\\'';
		}
		
		return token;
	}

	,render: function ()
	{
		var v = this._value;
	
		switch (typeof v)
		{
			case 'number':
				return v;
			case 'boolean':
				return (v) ? 'TRUE' : 'FALSE';
			case 'string':
				return "'" + v.replace (this.regexp, this.replaceFunc) + "'";
			case 'object':
			if (v instanceof Date)
				return Vn.Date.strftime (v, '\'%Y-%m-%d\'');
		}

		return 'NULL';
	}
});
