// XmlMemberValidation_StaticEnum.cpp
//

#include "stdafx.h"
#include "XmlBaseElement.h"
#include "XmlMemberValidation_StaticEnum.h"
#include "XmlMemberValidation_StaticEnumItem.h"

CXmlMemberValidation_StaticEnum::CXmlMemberValidation_StaticEnum()
{}

CXmlMemberValidation_StaticEnum::~CXmlMemberValidation_StaticEnum()
{
	Clear();
}

bool CXmlMemberValidation_StaticEnum::BuildFromXml(IXMLDOMNode* node)
{
	IXMLDOMNode* childNode;
	IXMLDOMNodeList* children;
	HRESULT hRes;
	long i;
	long size;
	CComBSTR nodeName;
	CComVariant nodeValue;

	Clear();

	hRes = node->get_childNodes(&children);
	
	children->get_length(&size);
	for (i = 0; i < size; i++) {
		hRes = children->get_item(i, &childNode);
		hRes = childNode->get_nodeName(&nodeName);
		hRes = childNode->get_nodeTypedValue(&nodeValue);

		if(CXmlMemberValidation_StaticEnumItem::GetXmlNodeName() == nodeName) {
			CXmlMemberValidation_StaticEnumItem* newItem;

			newItem = new CXmlMemberValidation_StaticEnumItem;
			newItem->BuildFromXml(childNode);

			items_.push_back(newItem);
		}
	}

	return true;
}

bool CXmlMemberValidation_StaticEnum::AppendToDOMDocument(IXMLDOMDocument2* xmlDoc, IXMLDOMElement* parentElement)
{
	IXMLDOMElement* newElement;
	bool ret = true;
	HRESULT hr;

	hr = xmlDoc->createElement(CComBSTR((const TCHAR*)GetXmlNodeName()), &newElement);

	// serialize members
	//
	CXmlMemberValidation_StaticEnumItem* item;
	
	for (int i = 0; i < items_.size(); i++) {
		item = items_[i];

		item->AppendToDOMDocument(xmlDoc, newElement);
	}
	
	// append node to parent element
	//
	if (parentElement)
		hr = parentElement->appendChild(newElement, NULL);
	else
		hr = xmlDoc->appendChild(newElement, NULL);

	return ret;
}

StaticEnumItems* CXmlMemberValidation_StaticEnum::GetItems()
{
	return &items_;
}

void CXmlMemberValidation_StaticEnum::AddEnumItem(const cmString& name, 
												  long enumValue,
												  const cmString& value, 
												  const cmString& description)
{
	CXmlMemberValidation_StaticEnumItem* item = NULL;

	for (int i = 0; i < items_.size(); i++) {
		if (items_[i]->GetItemName() == name) {
			item = items_[i];
			break;
		}
	}
	
	if (item == NULL) {
		item = new CXmlMemberValidation_StaticEnumItem;
		item->SetItemName(name);
		
		items_.push_back(item);
	}

	item->SetItemEnumValue(enumValue);
	item->SetItemValue(value);
	item->SetItemDescription(description);
}

void CXmlMemberValidation_StaticEnum::Clear()
{
	for (int i = 0; i < items_.size(); i++)
		delete items_[i];

	items_.clear();
}
	
void CXmlMemberValidation_StaticEnum::SetDefaults()
{}
