
#import "PhidgetAccelerometerController.h"
	
CPhidgetAccelerometerHandle accel;

@implementation PhidgetAccelerometerController

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 stringWithCString:error], nil]
							   waitUntilDone:NO];
	[pool release];
	return 0;
}

int gotAccel(CPhidgetAccelerometerHandle phid, void *context, int index, double value) {
	[(id)context gotAccelChange:index:value];
	return 0;
}

- (void)gotAccelChange:(int)index:(double)value
{
	int i=0;
	double out = 0;
	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	if(index == 0) {
		xaxis[6] = value;
		for(i=0;i<6;i++) {
			xaxis[i] = xaxis[i+1];
			out = out + xaxis[i];
		}
		[customView setX:out/6.0];
		[xField setFloatValue:out/6.0];
		//[customView setX:[accelInfo getVal]];
	}
	else if(index == 1){
		yaxis[6] = value;
		for(i=0;i<6;i++) {
			yaxis[i] = yaxis[i+1];
			out = out + yaxis[i];
		}
		[customView setY:out/6.0];
		[yField setFloatValue:out/6.0];
		//[customView setY:[accelInfo getVal]];
	}
	else {
		zaxis[6] = value;
		for(i=0;i<6;i++) {
			zaxis[i] = zaxis[i+1];
			out = out + zaxis[i];
		}
		[customView setZ:out/6.0];
		[zField setFloatValue:out/6.0];
		//[customView setZ:[accelInfo getVal]];
	}
	
	double xaxis1, yaxis1, zaxis1;
	CPhidgetAccelerometer_getAcceleration(accel, 0, &xaxis1);
	CPhidgetAccelerometer_getAcceleration(accel, 1, &yaxis1);
	CPhidgetAccelerometer_getAcceleration(accel, 2, &zaxis1);
	
	//printf("X: %2.4f Y: %2.4f Z: %2.4f\n",xaxis1,yaxis1,zaxis1);
	
    [customView setNeedsDisplay:YES];
	
	[pool release];
}

- (void)phidgetAdded
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	int serial, version;
	int numAxes;
	double accelMax, accelMin;
	const char *name;
	CPhidget_DeviceID devid;

	CPhidget_getSerialNumber((CPhidgetHandle)accel, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)accel, &version);
	CPhidget_getDeviceName((CPhidgetHandle)accel, &name);
	CPhidget_getDeviceID((CPhidgetHandle)accel, &devid);
	CPhidgetAccelerometer_getAxisCount(accel, &numAxes);
	CPhidgetAccelerometer_getAccelerationMax(accel, 0, &accelMax);
	CPhidgetAccelerometer_getAccelerationMin(accel, 0, &accelMin);
	
	[connectedField setStringValue:[NSString stringWithCString:name]];
	[serialNumberField setIntValue:serial];
	[versionField setIntValue:version];
	[numberOfAxesField setIntValue:numAxes];
	
	if(numAxes == 3)
	{
		[zLabel setHidden:FALSE];
		[zField setHidden:FALSE];
	}
	else
	{
		[zLabel setHidden:TRUE];
		[zField setHidden:TRUE];
	}
	
	if(accelMax == -accelMin)
		[rangeField setStringValue:[NSString stringWithFormat:@"+-%0.1lfg",accelMax]];
	else
		[rangeField setStringValue:[NSString stringWithFormat:@"%0.1lfg to %0.1lfg",accelMin,accelMax]];
	
	[sensorBox setHidden:FALSE];
	
	/* 540 = height we want + 20 */
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 540;
	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"];
	[serialNumberField setStringValue:@""];
	[versionField setStringValue:@""];
	[numberOfAxesField setStringValue:@""];
	[rangeField setStringValue:@""];
	
	[sensorBox setHidden:TRUE];
	
	/* 195 = height we want + 20 */
	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];
}

- (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)accel, serial, NULL, [[passwordField stringValue] UTF8String]);
	else
		CPhidget_open((CPhidgetHandle)accel, serial);
}

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

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

- (void)setPicture:(int)version:(CPhidget_DeviceID)devid
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSString *imgPath;
	
	switch(devid)
	{
		case PHIDID_ACCELEROMETER_2AXIS:
			imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1053_0" ofType:@"icns"];
			break;
		case PHIDID_ACCELEROMETER_3AXIS:
			imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1059_0" ofType:@"icns"];
			break;
		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)accel);
			[NSApp runModalForWindow:passwordPanel];
			break;
		case EEPHIDGET_BADVERSION:
			CPhidget_close((CPhidgetHandle)accel);
			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
