//
//  OutlineData.m
//  usblister
//
//  Created by Rex Feany on 4/8/11.
//  Copyright 2011 Fnordsoft, Inc. All rights reserved.
//

#import "OutlineData.h"


@implementation OutlineData

@synthesize data;

- (id)init {
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    return self;
}

- (void)dealloc {
    self.data = nil;
    [super dealloc];
}

static BOOL is_array(id item) {
    return ([item isKindOfClass:[NSArray class]]);
}

// How many children does this object have? 
- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item {
    // The root node is special; if the NSOutline view asks for the children of nil,
    // we give it the count of the root dictionary.
    if (item == nil) {
        return [self.data count];
    }
    
    // otherwise the item will be an array..
    if (is_array(item) && is_array([item objectAtIndex:1])) {
        return [[item objectAtIndex:1] count];
    }
    return 0;
}

// Can the item be expanded? If the value of the k/v pair is an array, yes!
- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item {
    if (is_array(item) && is_array([item objectAtIndex:1]))
        return YES;
    return NO;
}

// child at index of this item
- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(id)item {
    if (item == nil)
        return [data objectAtIndex:index];
    
    NSArray *row = [item objectAtIndex:1];
    
    if (is_array(row))
        return [row objectAtIndex:index];

    return nil;
}

// column data for child at index
- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item {
    if ([outlineView levelForItem:item] == 0) {
        if ([[tableColumn identifier] isEqualToString:@"name"]) {
            return [item objectAtIndex:0];
        }
    } else {
        
        if ([[tableColumn identifier] isEqualToString:@"name"]) {
            return [item objectAtIndex:0];
        }
        
        if ([[tableColumn identifier] isEqualToString:@"value"]) {
            if (is_array([item objectAtIndex:1])) {
                return @"";
            } else {
                return [item objectAtIndex:1];
            }
        }
    }
    return @"";
}

@end
