
var SqlObject = require('./object');

/**
 * List of Sql.Object
 */
module.exports = new Class({
	Extends: SqlObject

	,objects: []

	,add(object) {
		this.objects.push(object.ref());
		object.on('changed', this._onObjectChange, this);
		this._onObjectChange();
	}
	
	,get(i) {
		return objects[i];
	}
	
	,getArray() {
		return this.objects;
	}
	
	,remove(i) {
		this._unrefObject(this.objects.splice(i, 1));
		this._onObjectChange();
	}

	,_onObjectChange() {
		this.emit('changed');
	}

	,isReady() {
		var o = this.objects;
		
		if (o.length == 0)
			return false;
	
		for (var i = 0; i < o.length; i++)
		if (!o[i].isReady())
			return false;

		return true;
	}

	,findHolders() {
		let ids = [];

		for (const object of this.objects){
			holders = object.findHolders();
			if (holders) ids = ids.concat(holders);
		}

		return ids;
	}
	
	,_unrefObject(object) {
		object.disconnect('changed', this._onObjectChange, this);
		object.unref();
	}
	
	,_destroy() {
		for (var i = 0; i < this.objects.length; i++)
			this._unrefObject(this.objects[i]);
			
		SqlObject.prototype._destroy.call(this);
	}
});

