//
//  ECImageFilterSampleView.m
//  Etokicho
//
//  Created by 二鏡 on 11/11/28.
//  Copyright 2011年 二鏡庵. All rights reserved.
//

#import "ECCompositionSampleView.h"

@implementation ECCompositionSampleView
@synthesize target, time;
- (id)initWithFrame:(NSRect)frameRect
{
    self = [super initWithFrame: frameRect];
    
    time = 0;
    return self;
}

- (void)dealloc
{
    [transform release];
    [super dealloc];
}

- (BOOL)isOpaque
{
    return YES;
}

- (BOOL)acceptsFirstResponder
{
    return YES;
}

- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent
{
    return YES;
}

- (void)mouseDown:(NSEvent *)theEvent
{
    
}

- (void)setNeedsDisplay:(BOOL)flag
{
    [target forceEffectParameters]; 
    [super setNeedsDisplay: YES];
}

- (void)setContent:(ECScene*)aScene
       targetLayer:(NSUInteger)layerIndex
{
    [content release]; content = nil;
    [transform release]; transform = nil;
    if(aScene == nil)
        return ;

    content = [aScene copy];
    target = [[content layers] objectAtIndex: layerIndex];

    // シーンの大きさと自分の大きさを見て調整transformを決定
    NSRect bounds = [self bounds];
    NSSize size = content.size;
    
    // 縮小率を計算
    CGFloat scale_w = NSWidth(bounds)/size.width;
    CGFloat scale_h = NSHeight(bounds)/size.height;
    
    // 小さい方に合わせる
    CGFloat scale = MIN(scale_w,scale_h);
    
    // 拡大はしない
    if(scale > 1)
        scale = 1.0;
    
    CGFloat scaled_width = floor(size.width*scale);
    CGFloat scaled_height = floor(size.height*scale);
    
    CGFloat x = floor(NSWidth(bounds)-scaled_width)/2;
    CGFloat y = floor(NSHeight(bounds)-scaled_height)/2;
    
    transform = [[NSAffineTransform alloc] init];
    [transform translateXBy: x yBy: y];
    [transform scaleBy: scale];

    [self setNeedsDisplay: YES];
}

- (void)drawRect:(NSRect)dirtyRect
{
    [[NSColor blackColor] set];
    NSRectFill(dirtyRect);
    
    [transform concat];
    
    CGContextRef context = [[NSGraphicsContext currentContext] graphicsPort];
    CGImageRef image = [content allocImageAtTime: time];
    CGRect rect;
    rect.size = [content size];
    rect.origin = NSZeroPoint;

    if(image)
    {
        CGContextDrawImage(context, rect, image);
        CFRelease(image);
    }
}

@end
