// $Id: CWaxLibs.cc,v 1.2 2003/05/15 10:24:33 ta_muto Exp $

#include <CWaxLibs.h>
#include <CXmlLibs.h>

#include <CFileReader.h>

bool wax::CWaxLibs::parse(CEnvironment* runenv, xmlNodePtr cur, xmlChar*& content)
{
	content = NULL;
	if(!xmlStrcmp(cur->name, (const xmlChar*) "param-of")) {
		CXmlStr name(xmlGetProp(cur, (const xmlChar*) "name"));
		if(name.value() == NULL) {
			IError::message(ERR_ATTRIBUTE, "param-of::name");
			return false;
		}
		CRequest* request = runenv->getRequest();
		if(request == NULL) {
			IError::message(ERR_OUTOFMEMORY, LOCATION);
			return false;
		}
		CParameterItem* param = request->findParameter(name.value());
		if(param == NULL) {
			IError::message(ERR_NOTFOUNDPARAM, name.value());
			return false;
		}
		content = xmlStrdup(param->getOriginalValue());
	} else if(!xmlStrcmp(cur->name, (const xmlChar*) "system")) {
		CXmlStr environment(xmlGetProp(cur, (const xmlChar*) "environment"));
		if(environment.value() != NULL) {
			char* e = getenv((const char*) environment.value());
			if(e != NULL) {
				content = xmlStrdup((const xmlChar*)e);
			}
		} else {
			CXmlStr dateFormat(xmlGetProp(cur, (const xmlChar*) "now"));
			if(dateFormat.value() != NULL) {
				content = CXmlLibs::getDateTime(dateFormat.value());
			}
		}
	}
	return true;
}

bool wax::CWaxLibs::parseAsContent(CEnvironment* runenv, xmlNodePtr cur, xmlNsPtr ns, xmlChar*& content)
{
	while(cur != NULL) {
		if(cur->ns == ns) {
			xmlChar* value = NULL;
			if(parse(runenv, cur, value) == false) {
				return false;
			}
			if(value != NULL) {
				if(content == NULL) {
					content = xmlStrdup(value);
				} else {
					content = xmlStrcat(content, value);
				}
				xmlFree(value);
			}
		} else {
			switch(cur->type){
			case XML_TEXT_NODE:
				if(cur->content != NULL) {
					if(content == NULL) {
						content = xmlStrdup(cur->content);
					} else {
						content = xmlStrcat(content, cur->content);
					}
				}
				break;
			}
		}
		cur = cur->next;
	}
	return true;
}

xmlChar* wax::CWaxLibs::evaluateXPath(const xmlChar* connect, CCollection& vars, const xmlChar* expr)
{
	if(connect == NULL) {
		IError::message(ERR_CONNECT);
		return NULL;
	}
	CFileReader reader(connect);
	xmlDocPtr doc = CXmlLibs::read(&reader);
	if(doc == NULL)	return NULL;
	xmlChar* ret = evaluateXPath(doc, vars, expr);
	xmlFreeDoc(doc);
	return ret;
}

xmlChar* wax::CWaxLibs::evaluateXPath(xmlDocPtr doc, CCollection& vars, const xmlChar* expr)
{
	CXPathMacro macro(doc);
	
	CParameterItem* item = (CParameterItem*) vars.getHead();
	while(item != NULL) {
		macro.registerVariable(item->getName(), item->getOriginalValue());
		item = (CParameterItem*) item->getNext();
	}
	if(macro.evaluate(expr) == false) {
		IError::message(ERR_XPATH);
		return NULL;
	}
	return macro.getString();
}
