
#include "TimedTriples.h"

TTimedTriples::TTimedTriples()
 : input("")
{
}

TTimedTriples::TTimedTriples(const string& inp)
 : input(inp)
{
	toTimedTriples(input);
}

TTimedTriples::~TTimedTriples()
{
	triples.clear();
}

void TTimedTriples::Add(const string& inp)
{
	input.append(inp);
	toTimedTriples(inp);
}

void TTimedTriples::toTimedTriples()
{
	toTimedTriples(input);
}

void TTimedTriples::toTimedTriples(const string& inp)
{
	SSXMLParser parser(inp);
	SSXMLParser p("");

	while (true)
	{
		TTimedTriple triple;
		triple.inputStr = parser.getTag();
		if (triple.inputStr.empty())
		{
			break;
		}

		p.input = triple.inputStr;
		if (p.findName().compare("timedtriple") == 0)
		{
			triple.time = p.findAttrib("time=");
			triple.object = p.findAttrib("object=");
			triple.attribute = p.findAttrib("attribute=");
			triple.value = p.findAttrib("value=");
		}
		else
		{
			continue;
		}
		bool found = false;
		for (TTripleVector_it it = triples.begin(); it != triples.end(); it++)
		{
			if (((*it).object.compare(triple.object) == 0) &&
				((*it).attribute.compare(triple.attribute) == 0) &&
				((*it).value.compare(triple.value) == 0))
			{
				if (!(*it).time.compare(triple.time))
				{
					(*it).time = triple.time;
				}
				found = true;
				break;
			}
		}
		if (!found)
		{
			triples.push_back(triple);
#ifdef _DEBUG
			cerr << "TimedTriple(" << triple.time << ", " << triple.object << ", "
			     << triple.attribute << ", " << triple.value << ")" << endl;
#endif
		}
	}
}

bool TTimedTriples::getTimedTriple(TTimedTriple& triple, unsigned long time)
{
	for (TTripleVector_it it = triples.begin(); it != triples.end(); it++)
	{
		if ((unsigned long)(atol((*it).time.c_str())) != time)
		{
			triple = (*it);
			return true;
		}
	}
	return false;
}

bool TTimedTriples::getTimedTriple(TTimedTriple& triple, const string& time)
{
	for (TTripleVector_it it = triples.begin(); it != triples.end(); it++)
	{
		if ((*it).time.compare(time) == 0)
		{
			triple = (*it);
			return true;
		}
	}
	return false;
}

bool TTimedTriples::getTimedTriple(TTimedTriple& triple, const string &object,
	const string &attribute, const string &value)
{
	if (!object.empty() || !attribute.empty() || !value.empty())
	{
		for (TTripleVector_it it = triples.begin(); it != triples.end(); it++)
		{
			if ((object.empty() || (*it).object.compare(object) == 0) &&
				(attribute.empty() || (*it).attribute.compare(attribute) == 0) &&
				(value.empty() || (*it).value.compare(value) == 0))
			{
				triple = (*it);
				return true;
			}
		}
	}
	return false;
}
