#import "ProgramController.h"
#import "Program.h"

@implementation ProgramController

- (id)init
{
    NSConnection *serverConn;

    self = [super init];

    serverConn = [NSConnection
        connectionWithRegisteredName:@"ProgramServer" host:@"*"];
    programServer = [[serverConn rootProxy] retain];

    if (!programServer) {
        NSRunAlertPanel(@"No server",
            @"Can't connect to the program server.",
            @"Quit", nil, nil);
        [NSApp terminate:nil];
    }

    [(NSDistantObject *)programServer
        setProtocolForProxy:@protocol(ProgramServer)];

    programList = [[programServer programs] retain];
    return self;
}


- (void)updateList:(id)sender
{
    [programList release];
    programList = [[programServer programs] retain];
    [table reloadData];
    return;
}


- (void)tableClicked:(id)sender
{
    Program *selectedProgram;

    selectedProgram = [self selectedProgram];
    [channelField setStringValue:[selectedProgram channel]];
    [costField setStringValue:[selectedProgram cost]];

    return;
}


- (Program *)selectedProgram
{
    int row;
    Program *theProgram;

    row = [table selectedRow];
    theProgram = [programList objectAtIndex:row];
    return theProgram;
}

- (id <ProgramServer>)programServer
{
    return programServer;
}

- (int)numberOfRowsInTableView:(NSTableView *)tableView
{
    return [programList count];
}


- (id)tableView:(NSTableView *)tableView
    objectValueForTableColumn:(NSTableColumn *)tableColumn
    row:(int)row
{
    Program *theProgram = [programList objectAtIndex:row];
    id colID = [tableColumn identifier];

    if (!theProgram) return nil;
    if ([colID isEqual:@"title"]) return [theProgram title];
    else if ([colID isEqual:@"broadcastDate"]) {
        return [theProgram broadcastDate];
    }
    else return nil;
}


@end
