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

#import "MPFunctionTerm.h"

#import "MPFunction.h"



@interface MPFunctionTerm ()

@property (nonatomic, strong) NSArray *parsedExpressions;

@end



@implementation MPFunctionTerm

- (instancetype)initWithFunction:(MPFunction *)function
                          errors:(NSArray *__autoreleasing *)errors
{
    NSAssert(function != nil, @"function must not be nil.");
    if ([self isMemberOfClass:[MPFunctionTerm class]]) {
        return [[function.functionTermClass alloc] initWithFunction:function
                                                             errors:errors];
    }
    self = [super init];
    if (self) {
        NSMutableArray *parsedExpressions = [[NSMutableArray alloc] initWithCapacity:function.childrenAccessors.count];
        NSUInteger childIndex = 0;
        BOOL errorOccured = NO;
        NSMutableArray *mutableErrors = [[NSMutableArray alloc] init];
        for (NSString *accessor in function.childrenAccessors) {
            MPExpression *expression = [function valueForKey:accessor];
            NSArray *localErrors;
            MPParsedExpression *parsedExpression = [expression parseExpectingVariable:[function expectsVariableDefinitionInChildAtIndex:childIndex]
                                                                               errors:&localErrors];
            if (parsedExpression) {
                [parsedExpressions addObject:parsedExpression];
            } else {
                [mutableErrors addObjectsFromArray:localErrors];
                errorOccured = YES;
            }
            childIndex++;
        }
        if (errorOccured) {
            if (errors) {
                *errors = mutableErrors;
            }
            return nil;
        }
        self.parsedExpressions = parsedExpressions;
    }
    return self;
}


- (MPParsedExpression *)expressionAtIndex:(NSUInteger)anIndex
{
    return [self.parsedExpressions objectAtIndex:anIndex];
}

@end
