#include <libwccl/ops/match/matchoperator.h>
#include <libpwrutils/foreach.h>
#include <sstream>

namespace Wccl {

boost::shared_ptr<Match> MatchOperator::apply(
		boost::shared_ptr<Position> iter_pos,
		const FunExecContext& context) const
{
	boost::shared_ptr<MatchVector> matches(new MatchVector());
	int orig_iter_pos = iter_pos->get_value();

	foreach (const boost::shared_ptr<const MatchCondition>& cond, _conditions) {
		MatchResult res = cond->apply(iter_pos, context);
		if(res.matched()) {
			matches->append(res.get_match());
		} else {
			matches.reset(new MatchVector());
			iter_pos->set_value(orig_iter_pos + 1);
			return matches;
		}
	}
	return matches;
}

std::string MatchOperator::to_string(const Corpus2::Tagset& tagset) const
{
	std::ostringstream ostream;
	ostream << name() << "(";
	for(size_t i = 0; i < _conditions.size(); ++i) {
		if (i != 0) {
			ostream << ", ";
		}
		ostream << _conditions[i]->to_string(tagset);
	}
	ostream << ")";
	return ostream.str();
}

std::ostream& MatchOperator::write_to(std::ostream &ostream) const
{
	ostream << name() << "(";
	for(size_t i = 0; i < _conditions.size(); ++i) {
		if (i != 0) {
			ostream << ", ";
		}
		ostream << *_conditions[i];
	}
	ostream << ")";
	return ostream;
}

} /* end ns Wccl */