// XmlSerializable.cpp
//

#include "stdafx.h"
#include "XmlSerializable.h"

void CXmlSerializable::AppendMemberNode(const string& nodeName, 
										const string& nodeValue, 
										CXMLDOMElement& parentElement,
										CXMLDOMDocument2& xmlDoc)
{
	CXMLDOMElement member;

	member = xmlDoc.CreateElement(nodeName.c_str());
	member.SetText(nodeValue.c_str());
	parentElement.AppendChild(member);
}

void CXmlSerializable::AppendMemberNode(const string& nodeName, 
										 int nodeValue, 
										 CXMLDOMElement& parentElement,
										 CXMLDOMDocument2& xmlDoc)
{
	char buf[100];

	sprintf(buf, "%d", nodeValue);

	AppendMemberNode(nodeName, buf, parentElement, xmlDoc);
}

void CXmlSerializable::AppendMemberNode( const string& nodeName, 
										 double nodeValue, 
										 int precision,
										 CXMLDOMElement& parentElement,
										 CXMLDOMDocument2& xmlDoc)
{
	char buf[100];
	char format[20];

	sprintf(format, "%%1.%df", precision);
	sprintf(buf, format, nodeValue);

	AppendMemberNode(nodeName, buf, parentElement, xmlDoc);
}

bool CXmlSerializable::SaveToXmlFile(const string& fileName)
{
	CoInitialize(NULL);
	{
		CXMLDOMDocument2 xmlDoc;
		CXMLDOMProcessingInstruction pi;
		bool creationDone;
		
		creationDone = true;
		try
		{
			xmlDoc = CDOMDocument30Class::CreateXMLDOMDocument2();
		}
		catch (CComException *pE)
		{
			pE->Delete();
			
			creationDone = false;
		}

		if (creationDone) {
			pi = xmlDoc.CreateProcessingInstruction("xml", " version='1.0' encoding='ISO-8859-1'");
			xmlDoc.AppendChild(pi);

			CXMLDOMElement rootElement;
   
			AppendToDOMDocument(xmlDoc, rootElement, false);
   
			xmlDoc.Save(fileName.c_str());
		}
	}
	
	CoUninitialize();
	
	return true;
}

bool CXmlSerializable::LoadFromXmlFile(const string& fileName)
{
	BOOL ret;
   	string childName;
	
	CoInitialize(NULL);
	{
		CXMLDOMDocument2 xmlDoc;
		CXMLDOMNodeList childList;
		CXMLDOMNode child;
		bool creationDone;

		Clear();
		SetDefaults();
		
		creationDone = true;
		try
		{
			xmlDoc = CDOMDocument30Class::CreateXMLDOMDocument2();
		}
		catch (CComException *pE)
		{
			pE->Delete();
			
			creationDone = false;
			
		}

		if (creationDone) {

			ret = xmlDoc.Load(_variant_t(fileName.c_str()));
			
			if (ret) {
				childList = xmlDoc.GetChildNodes();

				ret = false;
				for (long i = 0; i < childList.GetLength(); i++) {
					child = childList.GetItem(i);
					childName = child.GetNodeName();

					if (childName == GetXmlNodeName().c_str())
						ret = BuildFromXml(child);
				}	
			} else {
				// TODO: display, log or notify someway the parser's error
				//
			}
		}   	
	}

	CoUninitialize();

	return (ret == TRUE);
}

string CXmlSerializable::GetXmlNodeName()
{
	return "";
}