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

#import "MPTerm.h"

#import "MPParsedExpression.h"
#import "MPEvaluationContext.h"



@implementation MPTerm

- (NSDecimalNumber *)evaluate:(NSError *__autoreleasing *)error
{
    [[MPEvaluationContext sharedContext] push];
    NSDecimalNumber *result = [self doEvaluation:error];
    [[MPEvaluationContext sharedContext] pop];
    return result;
}


- (BOOL)defineVariable:(NSString *)variableName
                 value:(NSDecimalNumber *)value
                 error:(NSError *__autoreleasing *)error
{
    BOOL couldDefineVariable = [[MPEvaluationContext sharedContext] defineVariable:variableName
                                                                             value:value];
    if (!couldDefineVariable) {
        if (error) {
            NSString *localizedDescription = [NSString stringWithFormat:NSLocalizedString(@"Redifinition of variable \"%@\".", nil), variableName];
            *error = [NSError errorWithDomain:MPMathKitErrorDomain
                                         code:100
                                     userInfo:@{NSLocalizedDescriptionKey: localizedDescription}];
        }
    }
    return couldDefineVariable;
}


- (NSDecimalNumber *)valueForVariable:(NSString *)variableName
                                error:(NSError *__autoreleasing *)error
{
    NSDecimalNumber *value = [[MPEvaluationContext sharedContext] valueForVariable:variableName];
    if (!value) {
        if (error) {
            NSString *localizedDescription = [NSString stringWithFormat:NSLocalizedString(@"Undefined variable \"%@\".", nil), variableName];
            *error = [NSError errorWithDomain:MPMathKitErrorDomain
                                         code:101
                                     userInfo:@{NSLocalizedDescriptionKey: localizedDescription}];
        }
    }
    return value;
}


- (void)undefineVariable:(NSString *)variableName
{
    [[MPEvaluationContext sharedContext] undefineVariable:variableName];
}

@end
