/*
** SellaNMS
** $Id: clause.cxx,v 1.7 2005/11/25 02:57:47 sella Exp $
** Copyright (c) 2001-2005 Digital Genesis Software, LLC. All Rights Reserved.
** Released under the GPL Version 2 License.
** http://www.digitalgenesis.com
*/

static const char rcsid[] = "$Id: clause.cxx,v 1.7 2005/11/25 02:57:47 sella Exp $";

#include "clause.h"
#include "common/snmp_util.h"

Clause::Clause(): storage(NULL) {
}

ACTION Clause::evaluate(slist<variable_binding_t> &v) {
	ACTION next_action = ACTION_NEXT_INPUT;

	for (slist<variable_binding_t>::iterator variable = v.begin(); variable != v.end(); ++variable) {
		if (ACTION_NEXT_INPUT == this->evaluate(*variable)) {
			return next_action;
		}
	}

	return next_action;
}

RESULT Clause::replaceVariables(variable_binding_t &variables, string &destination) {
	bool           is_variable = false;

	unsigned long  variable_begin;
	unsigned long  variable_size;

	unsigned long	replacements = 0;

	string         variable;

#if 0
	if (variables.find(destination) != variables.end()) {
		destination = variables[destination];
	}
#endif
	
	for (unsigned long location = 0; location < destination.size(); location++) {
		if (destination[location] == '@') {
			if (is_variable) {
				variable_size = location - variable_begin + 1;

				variable = destination.substr(variable_begin + 1, variable_size - 2);

				if (variables.find(variable) != variables.end()) {
					destination.replace(variable_begin, variable_size, variables[variable]);
					if (++replacements > MAX_VARIABLE_REPLACE) {
						LMSG("WARNING: input variable '%s' has a recursive value of '%s'.", variable.c_str(), variables[variable].c_str());

						replacements = 0;
					} else {
						location = variable_begin;
						if (destination[location] == '@') {
							is_variable = !is_variable;
						}
					}
				}
			} else {
				variable_begin = location;
			}
			is_variable = !is_variable;
		}
	}
	return SUCCESS;
}

bool Clause::containsVariable(string &value) {
	bool           is_variable = false;

	unsigned long  variable_begin;
	unsigned long  variable_size;

	unsigned long	magic_count = 0;

	for (unsigned long location = 0; location < value.size(); location++) {
		if (value[location] == '@') {
			if (is_variable) {
				variable_size = location - variable_begin + 1;
			} else {
				variable_begin = location;
			}
			is_variable = !is_variable;

			magic_count++;
		}
	}
	if (magic_count == 0) {
		return false;
	}
	if ((magic_count % 2) == 0) {
		return true;
	} else {
		return false;
	}
}

RESULT Clause::setStorage(Storage *storage) {
	this->storage = storage;

	return SUCCESS;
}

/*
** Local Variables:
** c-basic-offset: 3
** tab-width: 3
** End:
** vim600: fdm=marker
** vim: noet ts=3 sw=3 sts=3
*/
