//
//  MPDocument.m
//  MathPad
//
//  Created by Kim Wittenburg on 23.03.14.
//  Copyright (c) 2014 Kim Wittenburg. All rights reserved.
//

#import "MPDocument.h"



@implementation MPDocument {
    MPExpression *loadedExpression;
}

- (id)init
{
    self = [super init];
    if (self) {
        // Add your subclass-specific initialization here.
    }
    return self;
}


- (NSString *)windowNibName
{
    return @"MPDocument";
}


- (void)windowControllerDidLoadNib:(NSWindowController *)aController
{
    [super windowControllerDidLoadNib:aController];
    self.expressionView.target = self;
    self.expressionView.action = @selector(evaluateExpression:);
    if (loadedExpression) {
        [self.expressionView.expressionStorage appendElements:[loadedExpression allItemsInReferenceFrame:MPElementReferenceFrame]];
    }
}


+ (BOOL)autosavesInPlace
{
    return YES;
}


- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
    return [NSKeyedArchiver archivedDataWithRootObject:self.expressionView.expressionStorage];
}


- (BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError
{
    MPExpression *expression = [NSKeyedUnarchiver unarchiveObjectWithData:data];
    loadedExpression = expression;
    return YES;
}


#pragma mark Actions


- (IBAction)evaluateExpression:(id)sender {
    NSArray *errors;
    MPParsedExpression *parsedExpression = [self.expressionView.expressionStorage parse:&errors];
    NSError *mathError;
    NSDecimalNumber *result;
    if (parsedExpression) {
        result = [parsedExpression evaluate:&mathError];
    }
    self.expressionView.syntaxErrors = errors;
    self.expressionView.mathError = mathError;
    self.resultLabel.stringValue = result != nil ? [result descriptionWithLocale:[NSLocale currentLocale]] : @"";
}


@end
