#import "PhidgetServoController.h"
	
CPhidgetServoHandle servo;

@implementation PhidgetServoController

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

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

- (void)phidgetAdded
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	int serial, version, i;
	int numMotors;
	const char *name;
	CPhidget_DeviceID devid;
	int heightChange;
	double maxAngle, minAngle;

	CPhidget_getSerialNumber((CPhidgetHandle)servo, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)servo, &version);
	CPhidget_getDeviceName((CPhidgetHandle)servo, &name);
	CPhidget_getDeviceID((CPhidgetHandle)servo, &devid);
	CPhidgetServo_getMotorCount(servo,&numMotors);
	CPhidgetServo_getPositionMax(servo, 0, &maxAngle);
	CPhidgetServo_getPositionMin(servo, 0, &minAngle);
	
	CPhidgetServo_setEngaged(servo, 0, 1);
	
	[connectedField setStringValue:[NSString stringWithCString:name]];
	[serialField setIntValue:serial];
	[versionField setIntValue:version];
	[numberOfServosField setIntValue:numMotors];
	
	[servos renewRows:numMotors columns:1];
	[servoLables renewRows:numMotors columns:1];
	[servoFields renewRows:numMotors columns:1];
	[engageBoxes renewRows:numMotors columns:1];
	
	for(i=0;i<numMotors;i++)
	{
		double posn;
		int engaged;
		
		[[servos cellWithTag:i] setMinValue:minAngle];
		[[servos cellWithTag:i] setMaxValue:maxAngle];
		
		if(!CPhidgetServo_getPosition(servo, i, &posn))
		{
			[[servoFields cellWithTag:i] setStringValue:[NSString stringWithFormat:@"%0.1f", posn]];
			[[servos cellWithTag:i] setFloatValue:posn];
		}
		else
		{
			[[servoFields cellWithTag:i] setStringValue:@""];
			[[servos cellWithTag:i] setFloatValue:112.0];
		}
		
		if(!CPhidgetServo_getEngaged(servo, i, &engaged))
			[[engageBoxes cellWithTag:i] setState:engaged];
		else
			[[engageBoxes cellWithTag:i] setState:FALSE];
	}
	
	NSRect frame = [mainWindow frame];
	
	switch(devid)
	{
		case PHIDID_SERVO_1MOTOR_OLD:
		case PHIDID_SERVO_1MOTOR:
			heightChange = frame.size.height - 285;
			break;
		case PHIDID_SERVO_4MOTOR_OLD:
		case PHIDID_SERVO_4MOTOR:
			heightChange = frame.size.height - 354;
			break;
		default:
			break;
	}
	
	[servoBox setHidden:FALSE];
	
	frame.origin.y += heightChange;
	frame.size.height -= heightChange;
	[mainWindow setMinSize:frame.size];
	[mainWindow setFrame:frame display:YES animate:NO];
	
	[self setPicture:version:devid];
	[pool release];
	[mainWindow display];
}

- (void)phidgetRemoved
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	[connectedField setStringValue:@"Nothing"];
	[serialField setStringValue:@""];
	[versionField setStringValue:@""];
	[numberOfServosField setStringValue:@""];
	
	[servoBox setHidden:TRUE];
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 195;
	frame.origin.y += heightChange;
	frame.size.height -= heightChange;
	[mainWindow setMinSize:frame.size];
	[mainWindow setFrame:frame display:YES animate:NO];
	
	[self setPicture:0:0];
	
	[pool release];
	[mainWindow display];
}

- (IBAction)moveServo:(id)sender
{
	CPhidgetServo_setPosition(servo, [sender selectedTag], [[sender cellWithTag:[sender selectedTag]] floatValue]);
	[[servoFields cellWithTag:[sender selectedTag]] setStringValue:[NSString stringWithFormat:@"%0.1f", [[sender cellWithTag:[sender selectedTag]] floatValue]]];
	[[engageBoxes cellWithTag:[sender selectedTag]] setState:TRUE];
}

- (IBAction)engageServo:(id)sender
{
	CPhidgetServo_setEngaged(servo, [sender selectedTag], [[sender cellWithTag:[sender selectedTag]] state]);
}

/*
* This gets run when the GUI gets displayed
*/
- (void)awakeFromNib
{
	int serial = -1, remote = 0;
	NSArray *args = [[NSProcessInfo processInfo] arguments];
	if([args count] > 1)
	{
		if([[args objectAtIndex:1] isEqualToString:@"remote"])
			remote = 1;
		serial = strtol([[args objectAtIndex:[args count]-1] UTF8String], NULL, 10);
		if(serial == 0) serial = -1;
	}
	
	[mainWindow setDelegate:self];
	
	CPhidgetServo_create(&servo);
	
	CPhidget_set_OnAttach_Handler((CPhidgetHandle)servo, gotAttach, self);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)servo, gotDetach, self);
	
	if(remote)
		CPhidget_openRemote((CPhidgetHandle)servo, serial, NULL, NULL);
	else
		CPhidget_open((CPhidgetHandle)servo, serial);
}

- (void)windowWillClose:(NSNotification *)aNotification {
	CPhidget_close((CPhidgetHandle)servo);
	CPhidget_delete((CPhidgetHandle)servo);
	servo = NULL;
	[NSApp terminate:self];
}

- (void)setPicture:(int)version:(CPhidget_DeviceID)devid
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSString *imgPath;
	
	switch(devid)
	{
		case PHIDID_SERVO_1MOTOR:
			imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1000_0" ofType:@"icns"];
			break;
		case PHIDID_SERVO_4MOTOR:
			imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1001_0" ofType:@"icns"];
			break;
		case PHIDID_SERVO_1MOTOR_OLD:
		case PHIDID_SERVO_4MOTOR_OLD:
		default:
			imgPath = nil;
			break;
	}
	
	NSImage *img = [[NSImage alloc]  initByReferencingFile:imgPath];
	
	//otherwise the images are just painted over each other - and the transparency causes trouble
	[pictureBox setImage:nil];
	[pictureBox display];
	if(imgPath!=nil)
		[NSApp setApplicationIconImage: img];
	[pictureBox setImage:img];
	[pictureBox display];
	
	[pool release];
}
@end
