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

#import "MPFunctionLayout.h"
#import "MPFunction.h"
#import "MPExpressionLayout.h"

#import "MPSumFunction.h"
#import "MPSumFunctionLayout.h"

@implementation MPFunctionLayout

#pragma mark Creation Methods
+ (MPFunctionLayout *)functionLayoutForFunctionAtIndexPath:(NSIndexPath *)path
                                          inRootExpression:(MPExpression *)rootExpression
                                                    parent:(MPExpressionLayout *)parent
{
    MPFunction *function = [rootExpression elementAtIndexPath:path];
    Class class = [function class];
    if (class == [MPSumFunction class]) {
        return [[MPSumFunctionLayout alloc] initWithElementAtPath:path
                                                 inRootExpression:rootExpression
                                                           parent:parent];
    }
    return [[self alloc] initWithElementAtPath:path
                              inRootExpression:rootExpression
                                        parent:parent];
}

- (instancetype)initWithElementAtPath:(NSIndexPath *)path
                     inRootExpression:(MPExpression *)rootExpression
                               parent:(MPLayout *)parent
{
    self = [super initWithElementAtPath:path
                       inRootExpression:rootExpression
                                 parent:parent];
    if (self) {
        _function = [rootExpression elementAtIndexPath:path];
    }
    return self;
}

#pragma mark Cache Methods
- (CTLineRef)lineForPrivateCacheIndex:(NSUInteger)index
                            generator:(CTLineRef (^)())generator
{
    NSUInteger actualIndex = self.function.numberOfChildren + index;
    id (^actualGenerator)() = ^{
        CTLineRef line = generator();
        return CFBridgingRelease(line);
    };
    id lineObject = [self cachableObjectForIndex:actualIndex
                                       generator:actualGenerator];
    return (__bridge CTLineRef)(lineObject);
}

- (MPLayout *)childLayoutAtIndex:(NSUInteger)index
{
    return [self cachableObjectForIndex:index generator:^id{
        NSIndexPath *childPath = [self.function.indexPath indexPathByAddingIndex:index];
        MPExpressionLayout *layout = [[MPExpressionLayout alloc] initWithElementAtPath:childPath
                                                                      inRootExpression:self.function.rootExpression
                                                                                parent:self];
        layout.flipped = self.flipped;
        layout.usesSmallSize = (index == 0 || index == 1) ? YES : self.usesSmallSize;
        return layout;
    }];
}

#pragma mark Size and Drawing Methods
- (NSRect)generateBounds
{
    return NSZeroRect;
}

- (void)draw
{
    
}

@end
