var Connection = require('./connection');

module.exports = new Class({
	Extends: Vn.Object
	,Tag: 'db-query'
	,Properties: {
		/**
		 * The connection used to execute the statement.
		 */
		conn: {
			type: Connection
			,set(x) {
				this._conn = x;
				this.onChange();
			}
			,get() {
				return this._conn;
			}
		},
		/**
		 * The model query.
		 */
		query: {
			type: String
			,set(x) {
				this._stmt = new Sql.String({query: x});
				this.onChange();
			}
			,get() {
				return this._stmt.render(null);
			}
		},
		/**
		 * The model select statement.
		 */
		stmt: {
			type: Sql.Stmt
			,set(x) {
				this._stmt = x;
				this.onChange();
			}
			,get() {
				return this._stmt;
			}
		},
		/**
		 * The lot used to execute the statement.
		 */
		lot: {
			type: Vn.LotIface
			,set(x) {
				this.link({_lot: x}, {'change': this.onChange});
				this.onChange();
			}
			,get() {
				return this._lot;
			}
		},
		/**
		 * Wether to execute automatically de query que it's ready.
		 */
		autoLoad: {
			type: Boolean,
			value: false
		}
	}

	,appendChild(child) {
		if (child.nodeType === Node.TEXT_NODE)
			this.query = child.textContent;
	}

	,loadXml(builder, node) {
		Vn.Object.prototype.loadXml.call(this, builder, node);

		var query = node.firstChild.nodeValue;
		
		if (query)
			this.query = query;
	}
	
	,async execute() {
		const resultSet = await this._conn.execStmt(this._stmt, this._lot);
		this.emit('ready', resultSet);
		return resultSet;
	}
	
	,onChange() {
		if (this.autoLoad && this._conn && this._stmt && this._lot)
			this.execute();
	}
});