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

#import "ECCompositionWindowController.h"
#import "ECCompositionLayer.h"
#import "ECLayer_Defaults.h"

static id _si = nil;

static NSString *oLayerValueChanged = @"LayerValueChanged";

@implementation ECCompositionWindowController
@synthesize sceneView, composition;
+ (id)sharedCompositionWindow
{
    if(_si == nil)
    {
        _si = [[self alloc] initWithWindowNibName: @"Composition"];
        [_si window];
    }
    return _si;
}

- (void)awakeFromNib
{
    sceneView.editable = YES;
    [[self window] useOptimizedDrawing: YES];
    [self setWindowFrameAutosaveName: @"CompositionWindowFrame"];
}

- (void)setComposition:(id)comp
{
    // セットしっぱなしなので手を抜いている！
    composition = comp;
    
    [sceneView bind: @"selection"
           toObject: composition
        withKeyPath: @"selection"
            options: nil];
     
    [sceneView bind: @"content"
           toObject: composition
        withKeyPath: @"scene"
            options: nil];  
    [sceneView setComposition: comp];
    [composition addObserver: self
                  forKeyPath: @"update"
                     options: 0
                     context: oLayerValueChanged];
}

- (void)observeValueForKeyPath:(NSString *)keyPath 
                      ofObject:(id)object 
                        change:(NSDictionary *)change
                       context:(void *)context {
    if (context == oLayerValueChanged) {
        [sceneView setNeedsDisplay: YES];
        return;
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window
{
    // 最初の一回でキャッシュされちゃうので、絶対参照で打たないと共有できない
    return [[NSApp delegate] valueForKeyPath: @"composition.undo"];
}

- (void)addNewLayer:(ECLayer*)aLayer
{
    [composition.scene insertObject: aLayer inLayersAtIndex: 0];
}

- (IBAction)clear:(id)sender
{
    [composition clear];
}
@end
