/*
 * (C) Copyright 2002, Schlund+Partner AG
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

// Local configuration
#include "config.h"

// Implementation
#include "XMLNodeSet.hpp"

// STDC++
#include <cassert>

// C++ libaries
#include <ui-utilcpp/Text.hpp>

// Local
#include "XMLTree.hpp"
#include "../../src/ui-gxmlcpp/Util.hpp"

namespace UI {
namespace GXML {

XMLNodeSet::XMLNodeSet(std::string const & xpath, XMLTree const * tree)
{
	XPathContext context(tree->getDocPtr());

	_xPathObj = xmlXPathEval((xmlChar*)xpath.c_str(), context.get());

	// this seem never to happen...
	if (_xPathObj == 0)
	{
		UI_THROW_CODE(Eval_, "Could not evaluate XPath: " + xpath);
	}
	assert(_xPathObj);

	// happens if xpath doesn't point to node(s)
	if (_xPathObj->nodesetval == 0)
	{
		UI_THROW_CODE(NoSet_, "XPath delivers no node set: " + xpath);
	}
	assert(_xPathObj->nodesetval);

	// happens if xpath doesn't exist
	if (_xPathObj->nodesetval->nodeNr <= 0)
	{
		UI_THROW_CODE(NoMatch_, "XPath does not exist: " + xpath);
	}
	assert(_xPathObj->nodesetval->nodeNr > 0);
}

XMLNodeSet::~XMLNodeSet()
{
	xmlXPathFreeObject(_xPathObj);
}

int XMLNodeSet::size() const
{
	assert(_xPathObj && _xPathObj->nodesetval);
	return _xPathObj->nodesetval->nodeNr;
}

XMLNodeSet::Iterator XMLNodeSet::begin() const
{
	assert(_xPathObj && _xPathObj->nodesetval);
	return XMLNodeSet::Iterator(_xPathObj->nodesetval);
}

XMLNodeSet::Iterator XMLNodeSet::end() const
{
	return XMLNodeSet::Iterator();
}



XMLNodeSet::Iterator::Iterator()
	:_pos(0)
	,_set(0)
{}

XMLNodeSet::Iterator::Iterator(xmlNodeSetPtr const set)
	:_pos(0)
	,_set(set)
{}

XMLNodeSet::Iterator::~Iterator()
{}

XMLNodeSet::Iterator XMLNodeSet::Iterator::operator++()
{
	assert(_set);
	if (_pos < _set->nodeNr-1)
	{
		++_pos;
	}
	else
	{
		_pos = 0;
		_set = 0;
	}
	return *this;
}

bool XMLNodeSet::Iterator::operator!=(XMLNodeSet::Iterator const & iter) const
{
	if ((this->_pos != iter._pos) || (this->_set != iter._set))
	{
		return true;
	}
	else
	{
		return false;
	}
}

XMLNode XMLNodeSet::Iterator::operator *() const
{
	assert(_set && _set->nodeTab[_pos]);
	return XMLNode(_set->nodeTab[_pos]);
}

int
XMLNodeSet::Iterator::getPosition() const
{
	assert(_set);
	return _pos;
}

}}
