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

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

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

	,initialize(props) {
		Object.assign(this, {
			 _lastRow: 0
			,_lastReady: false
		});
		Iterator.prototype.initialize.call(this, props);
	}

	,onModelChange() {
		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(model, row) {
		if (row == this._row)
			this.rowChanged();
	}
});