//
//  MPSumFunctionTerm.m
//  MathKit
//
//  Created by Kim Wittenburg on 15.11.14.
//  Copyright (c) 2014 Kim Wittenburg. All rights reserved.
//

#import "MPSumFunctionTerm.h"

#import "MPParsedExpression.h"



@implementation MPSumFunctionTerm

- (NSDecimalNumber *)doEvaluation:(NSError *__autoreleasing *)error
{
    MPParsedExpression *startExpression = [self expressionAtIndex:0];
    NSDecimalNumber *start = [startExpression evaluate:error];
    ReturnNilIfNil(start);
    MPEvaluateExpression(target, 1);
    
    MPParsedExpression *sumExpression = [self expressionAtIndex:2];
    NSDecimalNumber *value = [NSDecimalNumber zero];
    for (NSDecimalNumber *current = start;
         [current compare:target] <= 0;
         current = [current decimalNumberByAdding:[[NSDecimalNumber alloc] initWithInteger:1]]) {
        if (![self defineVariable:startExpression.definedVariable value:current error:error]) {
            return nil;
        }
        NSDecimalNumber *currentValue = [sumExpression evaluate:error];
        ReturnNilIfNil(currentValue);
        value = [value decimalNumberByAdding:currentValue];
    }
    return value;
}

@end
