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

#import "MPFractionFunctionLayout.h"

#import "MPFractionFunction.h"


#define kFractionFunctionLineWidth 1.0
#define kFractionFunctionHorizontalInset 2.0
#define kFractionFunctionNominatorOffset 0
#define kFractionFunctionDenominatorOffset 0

#define MPFractionMiddle (CTFontGetCapHeight((CTFontRef)self.font) / 2)



@implementation MPFractionFunctionLayout

- (MPFractionFunction *)fractionFunction
{
    return (MPFractionFunction *)self.function;
}


- (NSUInteger)indexOfChildBelowChildAtIndex:(NSUInteger)index
{
    return 1;
}


- (NSUInteger)indexOfChildAboveChildAtIndex:(NSUInteger)index
{
    return 0;
}


- (NSIndexSet *)indexesOfRemainingChildren
{
    return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 2)];
}


- (NSPoint)offsetOfChildLayoutAtIndex:(NSUInteger)index
{
    NSRect bounds = self.bounds;
    if (index == 0) {
        NSRect numeratorBounds = [self childLayoutAtIndex:0].bounds;
        CGFloat y = MPFractionMiddle + kFractionFunctionLineWidth / 2 - numeratorBounds.origin.y;
        return NSMakePoint((bounds.size.width - numeratorBounds.size.width) / 2, y);
    } else {
        NSRect denominatorBounds = [self childLayoutAtIndex:1].bounds;
        CGFloat y = MPFractionMiddle - kFractionFunctionLineWidth / 2;
        y -= denominatorBounds.size.height + denominatorBounds.origin.y;
        return NSMakePoint((bounds.size.width - denominatorBounds.size.width) / 2, y);
    }
}


- (BOOL)childAtIndexUsesSmallSize:(NSUInteger)index
{
    return YES;
}


- (NSIndexPath *)indexPathForLocalMousePoint:(NSPoint)point
{
    if (point.x < self.bounds.size.width / 2) {
        return [NSIndexPath indexPathWithIndex:0];
    } else {
        return [NSIndexPath indexPathWithIndex:1];
    }
}


- (NSRect)generateBounds
{
    NSRect numeratorBounds = [self childLayoutAtIndex:0].bounds;
    NSRect denominatorBounds = [self childLayoutAtIndex:1].bounds;
    NSRect bounds;
    bounds.origin.x = 0;
    bounds.origin.y = MPFractionMiddle - kFractionFunctionLineWidth / 2 - denominatorBounds.size.height;
    bounds.size.width = MAX(numeratorBounds.size.width, denominatorBounds.size.width) + 2 * kFractionFunctionHorizontalInset;
    bounds.size.height = numeratorBounds.size.height + denominatorBounds.size.height + kFractionFunctionLineWidth;
    return bounds;
}


- (void)draw
{
    CGFloat y = MPFractionMiddle - kFractionFunctionLineWidth / 2;
    NSRectFill(NSMakeRect(0, y, self.bounds.size.width, kFractionFunctionLineWidth));
}

@end
