// $Id: CConfig.cc,v 1.8 2003/05/13 08:14:36 ta_muto Exp $

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

namespace wax {
	class CInternalConfig {
	public:
		CInternalConfig() { documentRoot = NULL, doc = NULL; }
		~CInternalConfig();
		
		bool init(const xmlChar* configPath);

		xmlChar* documentRoot;
		xmlDocPtr doc;
	} ;
	CInternalConfig* config = NULL;
}

bool wax::CInternalConfig::init(const xmlChar* configPath)
{
	// initialize variable of documentRoot.
	char* docRoot = getenv("DOCUMENT_ROOT");
	if(docRoot != NULL) {
		documentRoot = xmlStrdup((const xmlChar*)docRoot);
	} else {
		char* pathInfo = getenv("PATH_INFO");
		char* pathTranslated = getenv("PATH_TRANSLATED");
		if(pathInfo == NULL || pathTranslated == NULL) {
			documentRoot = NULL;
			IError::message(ERR_DOCUMENTROOT);
			return false;
		} else {
			int size = strlen(pathTranslated) - strlen(pathInfo);
			documentRoot = xmlStrndup((const xmlChar*)pathTranslated, size);
		}
	}
	// read configuration file.
	// It is not an error even when a file does not exist.
	if(config != NULL) {
		CFileReader reader(configPath);
		doc = CXmlLibs::read(&reader, false);
	}
	return true;
}

wax::CInternalConfig::~CInternalConfig()
{
	if(documentRoot != NULL)	xmlFree(documentRoot);
	if(doc != NULL)				xmlFreeDoc(doc);
}

bool wax::CConfig::init(const xmlChar* configPath)
{
	config = new CInternalConfig();
	if(config == NULL) {
		IError::message(ERR_OUTOFMEMORY, LOCATION);
		return false;
	}
	return config->init(configPath);
}

void wax::CConfig::free()
{
	if(config != NULL) {
		delete config;
		config = NULL;
	}
}

const xmlChar* wax::CConfig::getDocumentRoot()
{
	if(config == NULL)	return NULL;
	return config->documentRoot;
}

xmlDocPtr wax::CConfig::getConfig()
{
	if(config == NULL)	return NULL;
	return config->doc;
}
