//
//  EntityFieldListingManager.m
//  longspear
//
//  Created by Niko Matsakis on Thu Jul 15 2004.
//  Copyright (c) 2004 __MyCompanyName__. All rights reserved.
//

#import "EntityFieldListingManager.h"
#import "Actions.h"

@implementation EntityFieldListingManager

- initWithView:(NSTableView*)view delegate:delegate
{
    if ((self = [super init])) {
        _view = view; // weak ref
        _delegate = delegate;
        
        [_view setDataSource:self];
        [_view setDelegate:self];
    }
    return self;
}

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

- (void) setEntity:(Entity*)entity
{
    [_entity release];
    [_fieldListing release];
    
    if (!entity) {
        _entity = nil;
        _fieldListing = nil;
        return;
    }
        
    _entity = [entity retain];
    _fieldListing = [[NSMutableArray alloc] initWithCapacity:32];

    while (entity) {
        NSArray *fields = [entity fieldNames];
        NSEnumerator *enumer = [fields objectEnumerator];
        NSString *fieldname;
        while ((fieldname = [enumer nextObject])) {
            if (![_fieldListing containsObject:fieldname])
                [_fieldListing addObject:fieldname];
        }        
        
        entity = [entity base];
    }
    
    [_fieldListing sortUsingSelector:@selector(caseInsensitiveCompare:)];
    
    [_view reloadData];
}

- (int)numberOfRowsInTableView:(NSTableView *)aTableView
{
    assert (aTableView == _view);
    if (!_fieldListing) return 0;
    return [_fieldListing count];
}

- (id)tableView:(NSTableView *)aTableView 
objectValueForTableColumn:(NSTableColumn *)aTableColumn 
            row:(int)rowIndex;
{
    if (!_entity) {
        assert (!_fieldListing);
        return @""; /* not sure how this can happen */
    }

    NSString *fieldname = [_fieldListing objectAtIndex:rowIndex];

    if ([[aTableColumn identifier] isEqualToString:@"field"])
        return fieldname;
        
    return [_entity fieldAsString:fieldname];    
}

- (void)tableView:(NSTableView *)aTableView 
   setObjectValue:(id)anObject 
   forTableColumn:(NSTableColumn *)aTableColumn 
              row:(int)rowIndex
{
    assert (aTableView == _view);
    assert (_entity);
    
    NSString *fieldname = [_fieldListing objectAtIndex:rowIndex];
    [Action setFieldNamed:fieldname
                       to:anObject
                       on:_entity
                   target:_delegate];
}


@end
