// ******************************************************************
// ComponentManager.js
//
// Version 3.0
// Copyright (c) 2007 Catalog Data Solutions. All Rights Reserved.
//
// Class implementing components such as BoM or pricing based on
// attribute rules
// ******************************************************************

cds.namespace("configurator");

// ---------------------------------------------------------
// ComponentManager class
// ---------------------------------------------------------

cds.configurator.ComponentManager = function(attributeManager) {
	this.attributeManager = attributeManager;
	this.rules = new Array();

	this.addRule = function(name, value, order, expression) {
		this.rules[this.rules.length] = new cds.configurator.ComponentManagerRule(this.attributeManager, name, value, order, expression);
	};
	
	this.enforce = function() {
		var results = new Array();
		for (var i = 0; i < this.rules.length; i++) {
			var r = this.rules[i].enforce();
			if (r != null) {
				results[results.length] = r;
			}
		}
		return (results.length > 0) ? results.sort(this.sortResult) : null;
	};
	
	this.sortResult = function(a, b) {
		return a[2] - b[2];
	};
	
	this.destroy = function() {
		this.attributeManager = null;
		for (var i = 0; i < this.rules.length; i++) {
			if (typeof this.rules[i].destroy == "function") this.rules[i].destroy();
		}
		this.rules = null;
	};

	this.toString = function() {
		return "cds.configurator.ComponentManager";
	};
}

// ---------------------------------------------------------
// ComponentManagerRule class
// ---------------------------------------------------------

cds.configurator.ComponentManagerRule = function(attributeManager, name, value, order, expression) {
	this.name = name;
	this.value = value;
	this.order = order;
	this.evaluator = new cds.configurator.AttributeExpressionEvaluator(attributeManager, expression);

	this.enforce = function() {
		if (this.evaluator.evaluate()) {
			return [name, value, order];
		} else {
			return null;
		}
	};
	
	this.destroy = function() {
		this.evaluator = null;
	};

	this.toString = function() {
		var s = "cds.configurator.ComponentManagerRule(" + this.name + "," + this.value + ")";
		return s;
	};
}

