#import "WOTWViewController.h"

@implementation WOTWViewController

#pragma mark - Initialization / Memory Management

- (id)init {
    self = [super init];
    if (self) {
		[self loadPDF];
    }
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self loadPDF];
    }
    return self;
}

-(void)loadPDF
{
    CFURLRef pdfURL = CFBundleCopyResourceURL(CFBundleGetMainBundle(), CFSTR("WOTW.pdf"), NULL, NULL);
    bookPDF = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
    CFRelease(pdfURL);
}

- (void)dealloc
{
    CGPDFDocumentRelease(bookPDF);
    [super dealloc];
}

#pragma mark - LeavesViewDataSource methods

- (NSUInteger) numberOfPagesInLeavesView:(LeavesView*)leavesView {
	return CGPDFDocumentGetNumberOfPages(bookPDF);
}

- (void) renderPageAtIndex:(NSUInteger)index inContext:(CGContextRef)ctx {
	CGPDFPageRef page = CGPDFDocumentGetPage(bookPDF, index + 1);
	CGAffineTransform transform = aspectFit(CGPDFPageGetBoxRect(page, kCGPDFMediaBox),
											CGContextGetClipBoundingBox(ctx));
	CGContextConcatCTM(ctx, transform);
	CGContextDrawPDFPage(ctx, page);
}

@end
