// $Id: CEnvironment.cc,v 1.18 2003/05/10 06:46:48 ta_muto Exp $

#include <CEnvironment.h>
#include <CConfig.h>
#include <CFileReader.h>
#include <CHttpReader.h>
#include <CXmlLibs.h>

const xmlChar* wax::CEnvironment::WAX = (const xmlChar*) "http://www.info-db.net/wax";
const xmlChar* wax::CEnvironment::XUPDATE = (const xmlChar*) "http://www.xmldb.org/xupdate";
const xmlChar* wax::CEnvironment::XMLSCHEMA = (const xmlChar*) "http://www.w3.org/xmlschema";

wax::CEnvironment::CEnvironment(CRequest* req, bool initFlag)
{
	scriptPath = NULL;
	doc = NULL;
	root = NULL;
	request = req;
	startFlag = initFlag;
}

wax::CEnvironment::~CEnvironment()
{
	if(scriptPath != NULL)	xmlFree(scriptPath);
	if(doc != NULL)	xmlFreeDoc(doc);
}

bool wax::CEnvironment::prepare(const xmlChar* targetPath)
{
	scriptPath = trimPath(targetPath);
	CFileReader reader(targetPath);
	doc = CXmlLibs::read(&reader);
	if(doc == NULL) {
		return false;
	}
	root = xmlDocGetRootElement(doc);
	if(root == NULL) {
		IError::message(ERR_EMPTYDOCUMENT);
		return false;
	}
	return true;
}

xmlChar* wax::CEnvironment::makePath(const xmlChar* path)
{
	if(scriptPath == NULL)	return NULL;

	xmlChar* ret = NULL;
	if(path[0] == '/') {
		xmlChar* work = xmlStrdup(CConfig::getDocumentRoot());
		ret = xmlStrcat(work, path);
	} else {
		xmlChar* work = xmlStrdup(scriptPath);
		ret = xmlStrcat(work, path);
	}
	return ret;
}

wax::IReader* wax::CEnvironment::getReader(const xmlChar* href)
{
	return new CFileReader(href);
}
