#include "event/EventEnrichmentRule.h"
#include "expression/Expression.h"
#include "datatable/TableFormat.h"
#include "datatable/field/StringFieldFormat.h"
#include "datatable/validator/ValidatorHelper.h"
#include "datatable/validator/TableKeyFieldsValidator.h"
#include "GlobalVars.h"

TableFormatPtr EventEnrichmentRule::FORMAT_;

TableFormatPtr EventEnrichmentRule::FORMAT()
{
    if (!FORMAT_) {
        FORMAT_ = TableFormatPtr(new TableFormat());

        FORMAT_->addTableValidator(boost::shared_ptr<TableKeyFieldsValidator>(new TableKeyFieldsValidator()));

        FieldFormat *ff = FieldFormat::create("<"+AGG_GLOBAL.FIELD_NAME+"><S><F=K><D="+Cres::get()->getString("name")+">");
        ff->addValidator(ValidatorHelper::getInstance().getNAME_SYNTAX_VALIDATOR());
        ff->addValidator(ValidatorHelper::getInstance().getNAME_LENGTH_VALIDATOR());
        FORMAT_->addField(ff);
        FORMAT_->addField(FieldFormat::create("<"+AGG_GLOBAL.FIELD_EXPRESSION + "><S><D="+Cres::get()->getString("expression")
                                             +"><E="+AGG_GLOBAL.EDITOR_EXPRESSION+">"));
        FORMAT_->setNamingExpression("print({}, \"{"+AGG_GLOBAL.FIELD_NAME+"}\", \", \")");
    }

    return FORMAT_;
}

EventEnrichmentRule::EventEnrichmentRule()
    : AggreGateBean(FORMAT())
{ 
}


EventEnrichmentRule::EventEnrichmentRule(DataRecordPtr data) 
    : AggreGateBean(FORMAT(), data)
{
}


AgString EventEnrichmentRule::getName()
{
    return name;
}

void EventEnrichmentRule::setName(const AgString & name)
{
    this->name = name;
}

AgString EventEnrichmentRule::getExpression()
{
    return expression;
}

void EventEnrichmentRule::setExpression(const AgString & expression)
{
    this->expression = expression;
}

ExpressionPtr EventEnrichmentRule::getEnrichmentExpression()
{
    if(enrichmentExpression == NULL)
    {
        enrichmentExpression = (!expression.empty()) ? ExpressionPtr(new Expression(expression)) : ExpressionPtr();
    }
    return enrichmentExpression;
}


