// CategoryField.cpp
//

#include "stdafx.h"
#include "XmlGuiCategoryField.h"
#include "XmlClassInfo.h"
#include "XmlMemberInfo.h"

CXmlGuiCategoryField::CXmlGuiCategoryField():
	classInfo_(NULL)
{}

CXmlGuiCategoryField::~CXmlGuiCategoryField()
{}

void CXmlGuiCategoryField::SetMemberId(const cmString& memberId)
{
	memberId_ = memberId;
}

cmString CXmlGuiCategoryField::GetMemberId()
{
	return memberId_;
}

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

	Clear();
	
	hRes = node->get_childNodes(&children);
	hRes = 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(wcscmp(nodeName, _T("MemberId")) == 0) {
			memberId_ = nodeValue.bstrVal;
		} else if (wcscmp(nodeName, _T("Description")) == 0) {
			description_ = nodeValue.bstrVal;
			description_ = EscapeToPlainText(description_);
		}
	}

	return true;
}

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

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

	ret = CXmlBaseElement::AppendToDOMDocument(xmlDoc, newElement);
	if (!ret)
		return false;

	AppendMemberNode(_T("MemberId"), memberId_, newElement, xmlDoc);
	AppendMemberNode(_T("Description"), EscapeToXml(description_), newElement, xmlDoc);
	
	// append node to parent element
	//
	IXMLDOMNode* newOutNode;

	if (parentElement)
		hr = parentElement->appendChild(newElement, &newOutNode);
	else
		hr = xmlDoc->appendChild(newElement, &newOutNode);
	newOutNode->Release();

	return ret;
}

void CXmlGuiCategoryField::SetDescription(const cmString& description)
{
	description_ = description;
}

cmString CXmlGuiCategoryField::GetDescription()
{
	return description_;
}

void CXmlGuiCategoryField::SetClassInfo(CXmlClassInfo* classInfo)
{
	classInfo_ = classInfo;
}

cmString CXmlGuiCategoryField::GetCaption()
{
	CXmlMemberInfo* member;
	cmString caption;

	member = dynamic_cast<CXmlMemberInfo*>(classInfo_->GetMemberById(memberId_));
	if (member)
		caption = member->GetCaption();

	return caption; 
}

cmString CXmlGuiCategoryField::GetMemberName()
{
	CXmlMemberInfo* member;
	cmString name;

	member = dynamic_cast<CXmlMemberInfo*>(classInfo_->GetMemberById(memberId_));
	if (member)
		name = member->GetName();

	return name; 

}