#include <libwccl/ops/functions/position/lasttoken.h>
#include <libwccl/ops/functions/constant.h>
#include <libwccl/exception.h>
#include <sstream>

namespace Wccl {

LastToken::BaseRetValPtr LastToken::apply_internal(
	const FunExecContext &context) const
{
	boost::shared_ptr<Corpus2::AnnotatedSentence> s = 
		boost::dynamic_pointer_cast<Corpus2::AnnotatedSentence>(
			context.sentence_context().get_sentence_ptr());
	if (!s) {
		throw InvalidArgument(
			"context",
			"Supplied context does not have valid Corpus2::AnnotatedSentence.");
	}
	const Function<Match>::RetValPtr match = match_expr_->apply(context);
	if(match->empty()) {
		return detail::DefaultFunction<Position>()->apply(context);
	}
	return boost::make_shared<Position>(match->last_token(s));
}

std::string LastToken::to_string(const Corpus2::Tagset &tagset) const
{
	std::ostringstream ostream;
	ostream << name(tagset) << "(" << match_expr_->to_string(tagset) << ")";
	return ostream.str();
}

std::ostream& LastToken::write_to(std::ostream& ostream) const
{
	return ostream << raw_name() << "(" << *match_expr_ << ")";
}

} /* end ns Wccl */