#include "ofScraperXmlNode.h"


//--------------------------------------------------------------------------------------------
void printElementNames(xmlNode * a_node);  // helpful recursive printout...
void printElementNames(xmlNode * a_node, int level)
{
    xmlNode *cur_node = NULL;

    for (cur_node = a_node; cur_node; cur_node = cur_node->next) {
        if (cur_node->type == XML_ELEMENT_NODE) {
            for (int i = 0; i < level; i++){
            	printf(".");
            }
            printf("<%s>\n", cur_node->name);
        }
        printElementNames(cur_node->children, level+1);
    }
}

//--------------------------------------------------------------------------------------------
void ofScraperXmlNode::print(){
	if (myNode != NULL){
		printElementNames(myNode, 0);
	}
}


//--------------------------------------------------------------------------------------------
int ofScraperXmlNode::getNumChildren(){
	xmlNode *cur_node = NULL;
	int nChildren = 0;
    if (myNode != NULL){
	    for (cur_node = myNode->children; cur_node != NULL; cur_node = cur_node->next) {
	        if (cur_node->type == XML_ELEMENT_NODE) {
	           nChildren++;
	        }
	    }
    }
    return nChildren;
}

//--------------------------------------------------------------------------------------------
ofScraperXmlNode ofScraperXmlNode::getChild(int childNum){
	ofScraperXmlNode newNode;		
	
	xmlNode *cur_node = NULL;
	int nChildren = 0;
    if (myNode != NULL){
	    for (cur_node = myNode->children; cur_node != NULL; cur_node = cur_node->next) {
	        if (cur_node->type == XML_ELEMENT_NODE) {
	            if (nChildren == childNum){
	            	newNode.myNode = cur_node;
	            	break;
	            }
	           	nChildren++;
	          
	        }
	    }
    }
	return newNode;
}

//--------------------------------------------------------------------------------------------
string ofScraperXmlNode::getAttribute(string attribute){
	string result = "";
	if (myNode != NULL){
		xmlChar  * temp = (unsigned char *)xmlGetProp( myNode, (unsigned char *)attribute.c_str());
		if (temp != NULL){
			result = string((char *)temp);
			xmlFree(temp); 
		} 
	}
	return result;
}

//--------------------------------------------------------------------------------------------
string ofScraperXmlNode::getContent(){
	string result = "";
	if (myNode != NULL){
		xmlChar  * temp = xmlNodeGetContent( myNode);
		if (temp != NULL){
			result = string((char *)temp);
			xmlFree(temp);
		} 
	}
	return result;
}

//--------------------------------------------------------------------------------------------
bool ofScraperXmlNode::getHasAttribute(string attribute){
	if (myNode != NULL){
		return xmlHasProp( myNode, (unsigned char *)attribute.c_str());
	}
	return false;
}