#import "InspectorController.h"

@implementation InspectorController

+ (InspectorController *) sharedInspectorController
{
    static InspectorController *sharedObject = nil;

    if (sharedObject == nil)
        sharedObject = [[self alloc] init];
    return sharedObject;
}

- init
{
    [super init];
    inspectors = [[NSMutableArray alloc] initWithCapacity:2];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(revert:) name:NOTIFICATION_SELECTION_CHANGED object:nil];

    return self;
}

- (NSWindow *) panel
{
    if ([inspectorBox window] == nil)
        [NSBundle loadNibNamed:@"inspectorPanel.nib" owner:self];
    return [inspectorBox window];
}

- (void) registerInspector:(Inspector *)inspector
{
    [inspectors addObject:inspector];
}

- (void)revert:(id)sender
{
    NSEnumerator	*inspectorEnumerator;
    NSArray			*selection;
    BOOL			 found = NO;
    NSView			*view, *oldView;
    Inspector		*inspector = nil;

    if (![[self panel] isVisible])
        return;

    selection = [[[NSApplication sharedApplication] targetForAction:@selector(currentSelection)] currentSelection];
    inspectorEnumerator = [inspectors objectEnumerator];

    while (!found && (inspector = [inspectorEnumerator nextObject]))
        found = [inspector isValidInspectorForTargets:selection];

    if (found)
    {
        [inspector setTargets:selection];
        [inspector revert:nil];
        oldView = [inspectorBox contentView];
        view = [inspector view];
        if (oldView != view)
        {
            [inspectorBox setContentView:view];
            [[offWin contentView] addSubview:oldView];
        }
    }
    else if ([selection count] == 0)
        [inspectorBox setContentView:emptySelectionInspectorView];
    else
        NSLog (@"Unknown selection:%@", [selection description]);
}

@end
