
#import "PhidgetManagerController.h"
#import "Phidget.h"

@implementation PhidgetManagerController

CPhidgetManagerHandle phidm;

int gotAttach(CPhidgetHandle phid, void *context) {
	Phidget *phidget = [[Phidget alloc] initWithHandle:phid];
	[(id)context performSelectorOnMainThread:@selector(addDevice:)
								  withObject:phidget
							   waitUntilDone:YES];
	[phidget release];
	return 0;
}

int gotDetach(CPhidgetHandle phid, void *context) {
	Phidget *phidget = [[Phidget alloc] initWithHandle:phid];
	[(id)context performSelectorOnMainThread:@selector(removeDevice:)
								  withObject:phidget
							   waitUntilDone:YES];
	[phidget release];
	return 0;
}
	
/*
* This gets run when the GUI gets displayed
*/
- (void)awakeFromNib
{
	[mainWindow setDelegate:self];

    // Create the storage our table will use.
    devices = [[NSMutableArray alloc] init];
    // Be the data source... 
    [deviceTable setDataSource:self];
	
	CPhidget_enableLogging(PHIDGET_LOG_VERBOSE, NULL);
	
	CPhidgetManager_create(&phidm);
	/*
	* set up the phidget Manager - detects when phidgets are attached and removed
	*/
	CPhidgetManager_set_OnAttach_Handler(phidm, gotAttach, self);
	CPhidgetManager_set_OnDetach_Handler(phidm, gotDetach, self);
	
	CPhidgetManager_open(phidm);
	//CPhidgetManager_openRemote(phidm, NULL, NULL);
	//CPhidgetManager_openRemoteIP(phidm, "localhost", 5001, NULL);
	//CPhidgetManager_openRemoteIP(phidm, "192.168.3.150", 5001, NULL);
}

- (void)windowWillClose:(NSNotification *)aNotification {
	CPhidgetManager_close(phidm);
	CPhidgetManager_delete(phidm);
	phidm = NULL;
	[NSApp terminate:self];
}

- (void)addDevice:(Phidget *)phid {
    [devices addObject: phid];
    [deviceTable reloadData];
}

- (void)removeDevice:(Phidget *)phid {
    [devices removeObject: phid];
    [deviceTable reloadData];
}

// ---------------------------------------------------------
//  Data source methods
// ---------------------------------------------------------

- (int)numberOfRowsInTableView:(NSTableView *)tv {
    return [devices count];
}

- (id)tableView:(NSTableView *)tv objectValueForTableColumn:(NSTableColumn *)tc row:(int)row {
    if ([[tc identifier] isEqualToString:@"Phidget Name"]) {
        return [[devices objectAtIndex:row] phidgetName];
    } else if ([[tc identifier] isEqualToString:@"Phidget Serial"]) {
        return [[devices objectAtIndex:row] phidgetSerial];
    } else if ([[tc identifier] isEqualToString:@"Phidget Version"]) {
        return [[devices objectAtIndex:row] phidgetVersion];
    } else if ([[tc identifier] isEqualToString:@"Phidget Label"]) {
        return [[devices objectAtIndex:row] phidgetLabel];
    } else {
        return NULL;
    }
}

- (void)tableView:(NSTableView *)tv setObjectValue:(id)objectValue forTableColumn:(NSTableColumn *)tc row:(int)row {

}

@end