var Iterator = require('./iterator');
var Model = require('./model');

module.exports = new Class({
	Extends: Vn.Object
	,Implements: Iterator
	,Tag: 'db-form'
	,Properties: {
		/**
		 * The model associated to this form.
		 */
		model: { 
			type: Model
			,set(x) {
				this.link({_model: x}, {
					 'status-changed': this.onModelChange
					,'row-updated': this.onRowUpdate
				});
			}
			,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.iterChanged();
			}
			,get() {
				return this._row;
			}
		},
		/**
		 * The number of rows in the form.
		 */
		numRows: {
			type: Number
			,get() {
				if (this._model)
					return this._model.numRows;

				return 0;
			}
		},
		/**
		 * Checks if the form data is ready.
		 */
		ready: {
			type: Boolean
			,get() {
				return this._ready;
			}
		},
		/**
		 * The row object.
		 */
		$: {
			type: Object
			,get() {
				return this._model && this._model.getObject(this._row);
			}
		}
	}
	
	,lastRow: 0
	,_model: null
	,_row: -1
	,_ready: false

	,onModelChange() {
		var ready = this._model && this._model.ready;
		
		if (ready != this._ready) {
			if (this._row != -1)
				this.lastRow = this._row;
	
			this._ready = ready;
			this.emit('status-changed');
			
			if (this._row == -1)
				this.row = this.lastRow;
				
			if (ready)
				this.emit('ready');

			this.iterChanged();
		}
	}

	,onRowUpdate(model, row) {
		if (row == this._row)
			this.iterChanged();
	}
});