// $Id: CListener.cc,v 1.9 2003/05/10 06:46:51 ta_muto Exp $

#include <xupdate/CListener.h>
#include <xupdate/CXUpdate.h>
#include <CScriptlet.h>

wax::CListener::CListener()
{
	successScript = NULL;
	failedScript = NULL;
	disp = NULL;
}

wax::CListener::~CListener()
{
	if(successScript != NULL)	delete successScript;
	if(failedScript != NULL)	delete failedScript;
	if(disp != NULL)	delete disp;
}

bool wax::CListener::parse(CEnvironment* runenv, xmlNodePtr cur)
{
	xmlNsPtr ns = xmlSearchNsByHref(runenv->getDocPtr(), cur, CEnvironment::WAX);
	cur = cur->children;
	while(cur != NULL) {
		if(cur->ns == ns) {
			if(!xmlStrcmp(cur->name, (const xmlChar*) "success")) {
				successScript = parseInternal(runenv, cur);
				if(successScript == NULL)	return false;
			} else if(!xmlStrcmp(cur->name, (const xmlChar*) "failed")) {
				failedScript = parseInternal(runenv, cur);
				if(failedScript == NULL)	return false;
			}
		} else {
			xmlNsPtr nsXUpdate = xmlSearchNsByHref(runenv->getDocPtr(), cur, CEnvironment::XUPDATE);
			if(nsXUpdate != NULL) {
				CXUpdate* task = CXUpdate::getInstance(runenv, cur);
				taskList.addItem(task);
			}
		}
		cur = cur->next;
	}
	if(successScript == NULL) {
		IError::message(ERR_DIRECTION);
		return false;
	}
	return true;
}

wax::CEnvironment* wax::CListener::parseInternal(CEnvironment* runenv, xmlNodePtr cur)
{
	return NULL;
/*
	xmlChar* href = CXmlLibs::getUriOrDef(runenv, cur);
	if(href == NULL)	return NULL;
	
	CEnvironment* retEnv = new CEnvironment(runenv->getRequest(), true);
	if(retEnv == NULL) {
		xmlFree(href);
		IError::message(ERR_OUTOFMEMORY, LOCATION);
		return NULL;
	}
	if(retEnv->prepare(href) == false) {
		delete retEnv;
		retEnv = NULL;
	}
	xmlFree(href);
	return retEnv;
*/
}

bool wax::CListener::execute()
{
	ITask* task = (ITask*)taskList.getHead();
	while(task != NULL) {
		if(task->execute() == false) {
			if(failedScript != NULL) {
				disp = CScriptlet::parse(failedScript);
				if(disp == NULL)	return false;
				return disp->execute();
			} else {
				break;
			}
		}
		task = (ITask*)task->getNext();
	}
	disp = CScriptlet::parse(successScript);
	if(disp == NULL)	return false;
	return disp->execute();
}

void wax::CListener::output(IWriter* writer)
{
	if(disp != NULL)	disp->output(writer);
}
