
var Form = require ('./form');

module.exports = new Class
({
	Extends: Vn.Param
	,Tag: 'db-param'
	,Parent: 'form'
	,Properties:
	{
		/**
		 * The form field referenced by this param.
		 **/
		column:
		{
			type: String
			,set: function (x)
			{ 
				this._columnName = x;
				this.refresh ();
			}
			,get: function ()
			{
				this._columnName;
			}
		},
		/**
		 * The form referenced by this param.
		 **/
		form:
		{
			type: Form
			,set: function (x)
			{
				this.link ({_form: x},
				{
					 'status-changed': this.onFormChange
					,'iter-changed': this.onIterChange
				});

				this.refresh ();
			}
			,get: function ()
			{
				return this._form;
			}
		},
		/**
		 * Determines whether the link to the form is unidirectional, ie, a
		 * change in the form updates the parameter but not vice versa.
		 **/
		oneWay:
		{
			type: Boolean
			,set: function (x)
			{
				this._oneWay = x;
			}
			,get: function ()
			{
				return this._oneWay;
			}
		}
	}

	,_columnName: null
	,_form: null
	,_formLock: false
	,_columnIndex: -1
	,_oneWay: false
	,_formValue: null
	
	,initialize: function (props)
	{
		this.parent (props);
		this.on ('changed', this.onChange, this);
	}
	
	,refresh: function ()
	{
		if (this._form)
		{
			this.onFormChange ();
			this.onIterChange ();
		}
	}

	,onFormChange: function ()
	{
		if (this._columnName != null)
			this._columnIndex = this._form.getColumnIndex (this._columnName);
	}

	,onIterChange: function ()
	{
		this._formLock = true;
		
		var formValue;
	
		if (this._columnIndex !== -1)
			formValue = this._form.getByIndex (this._columnIndex);
		else
			formValue = undefined;
		
		this.value = formValue;		
		this._formLock = false;
	}

	,onChange: function ()
	{
		if (!this._formLock && this._columnIndex != -1 && !this.oneWay)
			this._form.setByIndex (this._columnIndex, this._value);
	}
});

