//
//  MPProductFunctionTerm.m
//  MathPad
//
//  Created by Kim Wittenburg on 10.01.15.
//  Copyright (c) 2015 Kim Wittenburg. All rights reserved.
//

#import "MPProductFunctionTerm.h"

#import "MPParsedExpression.h"



@implementation MPProductFunctionTerm

- (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 one];
    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 decimalNumberByMultiplyingBy:currentValue];
    }
    return value;
}

@end
