
var Iterator = require ('./iterator');
var ModelIface = require ('./model-iface');

module.exports = new Class
({
	Extends: Iterator
	,Tag: 'db-form'
	,Properties:
	{
		model:
		{ 
			type: ModelIface
			,set: function (x)
			{
				this.link ({_model: x},
				{
					 'status-changed': this.onModelChange
					,'row-updated': this.onModelRowUpdate
				});
			}
			,get: function ()
			{
				return this._model;
			}
		},
		/**
		 * The row where the form positioned, has -1 if the row is unselected.
		 */
		row:
		{ 
			type: Number
			,set: function (x)
			{
				if (!this._model || this._model.numRows <= x || x < -1)
					x = -1;
				if (x == this._row)
					return;

				this._row = x;
				this.rowChanged ();
			}
			,get: function ()
			{
				return this._row;
			}
		}
	}

	,initialize: function (props)
	{
		Object.assign (this, {
			 _lastRow: 0
			,_lastReady: false
		});
		this.parent (props);
	}

	,onModelChange: function ()
	{
		var ready = this._model && this._model.ready;
		
		if (ready != this._lastReady)
		{
			if (this._row != -1)
				this._lastRow = this._row;
	
			this._lastReady = ready;
			this.emit ('status-changed');
			
			if (this._row == -1)
				this.row = this._lastRow;
				
			if (ready)
				this.emit ('ready');
		}
	}

	,onModelRowUpdate: function (model, row)
	{
		if (row == this._row)
			this.rowChanged();
	}
});
