#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;
}

int gotError(CPhidgetHandle phid, void *context, int errcode, const char *error) {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[(id)context performSelectorOnMainThread:@selector(ErrorEvent:)
								  withObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:errcode], [NSString stringWithUTF8String:error], nil]
							   waitUntilDone:NO];
	[pool release];
	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 stringWithUTF8String: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]);
}

- (void)openCmdLine
{
	int serial = -1, remote = 0;
	NSArray *args = [[NSProcessInfo processInfo] arguments];
	if([args count] > 1)
	{
		if([[args objectAtIndex:1] isEqualToString:@"remote"])
			remote = 1;
		serial = [[args objectAtIndex:[args count]-1] intValue];
		if(serial == 0) serial = -1;
	}
	
	if(remote)
		CPhidget_openRemote((CPhidgetHandle)servo, serial, NULL, [[passwordField stringValue] UTF8String]);
	else
		CPhidget_open((CPhidgetHandle)servo, serial);
}

/*
* This gets run when the GUI gets displayed
*/
- (void)awakeFromNib
{
	[mainWindow setDelegate:self];
	
	CPhidgetServo_create(&servo);
	
	CPhidget_set_OnAttach_Handler((CPhidgetHandle)servo, gotAttach, self);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)servo, gotDetach, self);
	CPhidget_set_OnError_Handler((CPhidgetHandle)servo, gotError, self);
	
	[self openCmdLine];
}

- (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];
}

int errorCounter = 0;
- (void)ErrorEvent:(NSArray *)errorEventData
{
	int errorCode = [[errorEventData objectAtIndex:0] intValue];
	NSString *errorString = [errorEventData objectAtIndex:1];
	
	switch(errorCode)
	{
		case EEPHIDGET_BADPASSWORD:
			CPhidget_close((CPhidgetHandle)servo);
			[NSApp runModalForWindow:passwordPanel];
			break;
		case EEPHIDGET_BADVERSION:
			CPhidget_close((CPhidgetHandle)servo);
			NSRunAlertPanel(@"Version mismatch", [NSString stringWithFormat:@"%@\nApplication will now close.", errorString], nil, nil, nil);
			[NSApp terminate:self];
			break;
		default:
			errorCounter++;
			
			NSAttributedString *string = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n",errorString]];
			
			[[errorEventLog textStorage] beginEditing];
			[[errorEventLog textStorage] appendAttributedString:string];
			[[errorEventLog textStorage] endEditing];
			
			[errorEventLogCounter setIntValue:errorCounter];
			if(![errorEventLogWindow isVisible])
				[errorEventLogWindow setIsVisible:YES];
			break;
	}
}

- (IBAction)clearErrorLog:(id)sender
{
	[[errorEventLog textStorage] setAttributedString:[[NSAttributedString alloc] initWithString:@""]];
	[errorEventLogCounter setIntValue:0];
	errorCounter = 0;
}

- (IBAction)passwordOK:(id)sender
{
	[passwordPanel setIsVisible:NO];
	[NSApp stopModal];
	[self openCmdLine];
	[passwordField setStringValue:@""];
}

- (IBAction)passwordCancel:(id)sender
{
	[passwordPanel setIsVisible:NO];
	[NSApp stopModal];
	[NSApp terminate:self];
}
@end
