#include <libwccl/ops/functions/strset/affix.h>
#include <sstream>
#include <libpwrutils/foreach.h>

namespace Wccl {

std::string Affix::to_string(const Corpus2::Tagset& tagset) const
{
	std::stringstream str;
	str << name(tagset) << "(" << strset_expr_->to_string(tagset)
		<< ", " << affix_length_ << ")";
	return str.str();
}

std::string Affix::to_raw_string() const {
	std::stringstream str;
	str << raw_name() << "(" << strset_expr_->to_raw_string()
		<< ", " << affix_length_ << ")";
	return str.str();
}

Affix::BaseRetValPtr Affix::apply_internal(const FunExecContext& context) const
{
	if(affix_length_ == 0) {
		return strset_expr_->apply(context);
	}
	const boost::shared_ptr<const StrSet>& set = strset_expr_->apply(context);
	boost::shared_ptr<StrSet> a_set = boost::shared_ptr<StrSet>(new StrSet());
	if(affix_length_ < 0) {
		foreach(const UnicodeString& s, set->contents()) {
			a_set->insert(UnicodeString(s).remove(0, s.length() + affix_length_));
		}
	} else {
		foreach(const UnicodeString& s, set->contents()) {
			UnicodeString prefixed(s);
			prefixed.truncate(affix_length_);
			a_set->insert(prefixed);
		}
	}
	return a_set;
}

} /* end ns Wccl */