#import "LabelUtilityController.h"
#import "TableData.h"

@implementation LabelUtilityController

CPhidgetManagerHandle phidm;

- (IBAction)setLabel:(id)sender
{
	CPhidgetHandle phid;
	const char *label;
	char newLabel[11];
	long serial;
	char deviceName[100], temp[50];
	
	if([labelsTable selectedRow]>=0) {
		strcpy(deviceName, [[[labels objectAtIndex:[labelsTable selectedRow]] phidgetType] UTF8String]);
		
		if (!strcmp(deviceName, "PhidgetInterfaceKit")) { if(CPhidgetInterfaceKit_create((CPhidgetInterfaceKitHandle *)&phid)) return;}
		else if (!strcmp(deviceName, "PhidgetServo")) { if(CPhidgetServo_create((CPhidgetServoHandle *)&phid)) return;}
		else if (!strcmp(deviceName, "PhidgetRFID")) { if(CPhidgetRFID_create((CPhidgetRFIDHandle *)&phid)) return;}
		else if (!strcmp(deviceName, "PhidgetWeightSensor")) { if(CPhidgetWeightSensor_create((CPhidgetWeightSensorHandle *)&phid)) return;}
		else if (!strcmp(deviceName, "PhidgetTextLCD")) { if(CPhidgetTextLCD_create((CPhidgetTextLCDHandle *)&phid)) return;}
		else if (!strcmp(deviceName, "PhidgetMotorControl")) { if(CPhidgetMotorControl_create((CPhidgetMotorControlHandle *)&phid)) return;}
		else if (!strcmp(deviceName, "PhidgetLED")) { if(CPhidgetLED_create((CPhidgetLEDHandle *)&phid)) return;}
		else if (!strcmp(deviceName, "PhidgetEncoder")) { if(CPhidgetEncoder_create((CPhidgetEncoderHandle *)&phid)) return;}
		else if (!strcmp(deviceName, "PhidgetStepper")) { if(CPhidgetStepper_create((CPhidgetStepperHandle *)&phid)) return;}
		else if (!strcmp(deviceName, "PhidgetTemperatureSensor")) { if(CPhidgetTemperatureSensor_create((CPhidgetTemperatureSensorHandle *)&phid)) return;}
		else if (!strcmp(deviceName, "PhidgetAccelerometer")) { if(CPhidgetAccelerometer_create((CPhidgetAccelerometerHandle *)&phid)) return;}
		else if (!strcmp(deviceName, "PhidgetTextLED")) { if(CPhidgetTextLED_create((CPhidgetTextLEDHandle *)&phid)) return;}
		else if (!strcmp(deviceName, "PhidgetPHSensor")) { if(CPhidgetPHSensor_create((CPhidgetPHSensorHandle *)&phid)) return;}
		//else if (!strcmp(deviceName, "PhidgetGyroscope")) { if(CPhidgetGyroscope_create(&phid)) return;}
		else if (!strcmp(deviceName, "PhidgetAdvancedServo")) { if(CPhidgetAdvancedServo_create((CPhidgetAdvancedServoHandle *)&phid)) return;}
		//else if (!strcmp(deviceName, "PhidgetGPS")) { if(CPhidgetGPS_create(&phid)) return;}
		else {printf("Bad Device Type\n"); return;}
		
		strcpy(temp, [[[labels objectAtIndex:[labelsTable selectedRow]] phidgetSerial] UTF8String]);
		serial = atoi(temp);
		
		if(CPhidget_open(phid, serial)) {
			NSRunAlertPanel(@"Problem setting label", @"The device could not be opened.\nIt is probably being used by another program.", nil, nil, nil);
			CPhidget_delete(phid);
			return;
		}	
		if(strlen([[labelField stringValue] UTF8String]) > 10) {
			NSRunAlertPanel(@"Problem setting label", @"The String size must be 10 characters or less.", nil, nil, nil);
			CPhidget_close(phid);
			CPhidget_delete(phid);
			return;
		}
		strcpy(newLabel, [[labelField stringValue] UTF8String]);
		if(CPhidget_waitForAttachment(phid, 1000)) {
			NSRunAlertPanel(@"Problem setting label", @"The Phidget is not being reported as opened...", nil, nil, nil);
			CPhidget_close(phid);
			CPhidget_delete(phid);
			return;
		}
		if(CPhidget_setDeviceLabel(phid, newLabel)) {
			NSRunAlertPanel(@"Problem setting label", @"Couldn't set the label.\nThis device probably doesn't support labels.", nil, nil, nil);
		}
		CPhidget_getDeviceLabel(phid, &label);
		[[labels objectAtIndex:[labelsTable selectedRow]] setPhidgetLabel:[NSString stringWithCString:label]];
		[labelsTable reloadData];
		CPhidget_close(phid);
		CPhidget_delete(phid);
	}
	else {
		printf("Nothing selected\n");
	}

}

int gotAttach(CPhidgetHandle phid, void *context) {
	[(id)context addDevice:phid];
	return 0;
}

int gotDetach(CPhidgetHandle phid, void *context) {
	[(id)context removeDevice:phid];
	return 0;
}

/*
* This gets run when the GUI gets displayed
*/
- (void)awakeFromNib
{
	[mainWindow setDelegate:self];

    // Create the storage our table will use.
    labels = [[NSMutableArray alloc] init];
    // Be the data source... 
    [labelsTable setDataSource:self];
	
	/*
	* set up the phidget Manager - detects when phidgets are attached and removed
	*/
	CPhidgetManager_create(&phidm);
	CPhidgetManager_set_OnAttach_Handler(phidm, gotAttach, self);
	CPhidgetManager_set_OnDetach_Handler(phidm, gotDetach, self);
	CPhidgetManager_open(phidm);
}

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

- (void)addDevice:(CPhidgetHandle)phid {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    // Append a newly created data object, then reload the table contents.
	const char *phidgetName, *phidgetType;
	const char *phidgetLabel;
	int phidgetSerial;
	int phidgetVersion;
	
	CPhidget_getDeviceName(phid,&phidgetName);
	CPhidget_getDeviceType(phid,&phidgetType);
	CPhidget_getSerialNumber(phid, &phidgetSerial);
	CPhidget_getDeviceVersion(phid, &phidgetVersion);
	CPhidget_getDeviceLabel(phid, &phidgetLabel);
	
    TableData *tableData = [[TableData alloc] init];
	
	[tableData setPhidgetName:[NSString stringWithCString:phidgetName]];
	[tableData setPhidgetType:[NSString stringWithCString:phidgetType]];
	[tableData setPhidgetLabel:[NSString stringWithCString:phidgetLabel]];
	[tableData setPhidgetSerial:[NSString stringWithFormat:@"%ld", phidgetSerial]];
	[tableData setPhidgetVersion:[NSString stringWithFormat:@"%ld", phidgetVersion]];
	
    [labels addObject: tableData];
    [tableData release];
    [labelsTable reloadData];
	[pool release];
}

- (void)removeDevice:(CPhidgetHandle)phid {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    // Append a newly created data object, then reload the table contents.
	const char *phidgetName, *phidgetType;
	const char *phidgetLabel;
	int phidgetSerial;
	int phidgetVersion;
	
	CPhidget_getDeviceName(phid,&phidgetName);
	CPhidget_getDeviceType(phid,&phidgetType);
	CPhidget_getSerialNumber(phid, &phidgetSerial);
	CPhidget_getDeviceVersion(phid, &phidgetVersion);
	CPhidget_getDeviceLabel(phid, &phidgetLabel);
	
    TableData *tableData = [[TableData alloc] init];
	
	[tableData setPhidgetName:[NSString stringWithCString:phidgetName]];
	[tableData setPhidgetType:[NSString stringWithCString:phidgetType]];
	[tableData setPhidgetLabel:[NSString stringWithCString:phidgetLabel]];
	[tableData setPhidgetSerial:[NSString stringWithFormat:@"%ld", phidgetSerial]];
	[tableData setPhidgetVersion:[NSString stringWithFormat:@"%ld", phidgetVersion]];
	
    [labels removeObject: tableData];
    [tableData release];
    [labelsTable reloadData];
	[pool release];
}

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

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

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

- (void)tableView:(NSTableView *)tv setObjectValue:(id)objectValue forTableColumn:(NSTableColumn *)tc row:(int)row {
    if ([[tc identifier] isEqualToString:@"Phidget Name"]) {
        [[labels objectAtIndex:row] setPhidgetName: objectValue];
    } else if ([[tc identifier] isEqualToString:@"Phidget Serial"]) {
        [[labels objectAtIndex:row] setPhidgetSerial: objectValue];
    } else if ([[tc identifier] isEqualToString:@"Phidget Version"]) {
        [[labels objectAtIndex:row] setPhidgetVersion: objectValue];
    } else if ([[tc identifier] isEqualToString:@"Phidget Label"]) {
        [[labels objectAtIndex:row] setPhidgetLabel: objectValue];
    } else {;}
}

@end
