#include "datatable/validator/TableExpressionValidator.h"
#include "AggreGateException.h"
#include "expression/Evaluator.h"
#include "expression/Expression.h"
#include "datatable/TableFormat.h"
#include "datatable/ValidationException.h"
#include "util/Log.h"

TableExpressionValidator::TableExpressionValidator(const AgString& expression)
{
    this->expression = ExpressionPtr(new Expression(expression));
}

TableExpressionValidator *TableExpressionValidator::clone()
{
    TableExpressionValidator *tev = new TableExpressionValidator(expression->getText());
    return tev;
}

char TableExpressionValidator::getType()
{
    return TableFormat::TABLE_VALIDATOR_EXPRESSION;
}

AgString TableExpressionValidator::encode()
{
    return expression->getText();
}

void TableExpressionValidator::validate(DataTablePtr table)
{
    EvaluatorPtr evaluator = EvaluatorPtr(new Evaluator(table));

    try
    {
        AgObjectPtr result = evaluator->evaluate(expression);

        if (result.get() != NULL)
        {
            throw ValidationException(result->toString());
        }
    }
    catch (ValidationException ex)
    {
        throw ex;
    }
    catch (AggreGateException ex)
    {
        LOG_DATATABLE_DEBUG("Error evaluating data table validator's expression '" + expression->toString().toUtf8() + "': " + ex.getMessage().toUtf8());
    }
}
