#import "PhidgetGPSController.h"

//Event callback functions for C, which in turn call a method on the GUI object in it's thread context
int gotAttach(CPhidgetHandle phid, void *context) {
	[(id)context performSelectorOnMainThread:@selector(phidgetAdded:)
								  withObject:nil
							   waitUntilDone:NO];
	return 0;
}
int gotDetach(CPhidgetHandle phid, void *context) {
	[(id)context performSelectorOnMainThread:@selector(phidgetRemoved:)
								  withObject:nil
							   waitUntilDone:NO];
	return 0;
}

int gotPositionChange(CPhidgetGPSHandle phid, void *context, double latitude, double longitude, double altitude) {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[(id)context performSelectorOnMainThread:@selector(PositionChange:)
								  withObject:[NSArray arrayWithObjects:[NSNumber numberWithDouble:latitude], [NSNumber numberWithDouble:longitude], [NSNumber numberWithDouble:altitude], nil]
							   waitUntilDone:NO];
	[pool release];
	return 0;
}
int gotPositionFixStatusChange(CPhidgetGPSHandle phid, void *context, int fix) {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[(id)context performSelectorOnMainThread:@selector(PositionFixStatusChange:)
								  withObject:[NSNumber numberWithInt:fix]
							   waitUntilDone:NO];
	[pool release];
	return 0;
}


@implementation PhidgetGPSController

- (void)setPicture:(int)version:(CPhidget_DeviceID)devid
{
	NSImage *img = nil;
	
	switch(devid)
	{
		case PHIDID_GPS:
			img = [NSImage imageNamed:@"1040_0"];
			break;
		default:
			break;
	}
	
	//don't set the dock icon to nil
	if(img)
		[NSApp setApplicationIconImage:img];
	
	//ok to set the picture to nil
	[pictureBox setImage:img];
}

- (void)phidgetAdded:(id)nothing
{
	int serial, version;
	const char *name;
	CPhidget_DeviceID devid;
	
	CPhidget_getSerialNumber((CPhidgetHandle)gps, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)gps, &version);
	CPhidget_getDeviceName((CPhidgetHandle)gps, &name);
	CPhidget_getDeviceID((CPhidgetHandle)gps, &devid);
	
	[connectedField setStringValue:[NSString stringWithCString:name]];
	[serialField setIntValue:serial];
	[versionField setIntValue:version];
	
	[gpsBox setHidden:FALSE];
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 325;
	
	frame = [mainWindow frame];
	frame.origin.y += heightChange;
	frame.size.height -= heightChange;
	[mainWindow setMinSize:frame.size];
	[mainWindow setFrame:frame display:YES animate:NO];
	
	[self setPicture:version:devid];
}

- (void)phidgetRemoved:(id)nothing
{
	[connectedField setStringValue:@"Nothing"];
	[serialField setStringValue:@""];
	[versionField setStringValue:@""];
	
	[fixStatus setState:0];
	[latitudeField setStringValue:@""];
	[longitudeField setStringValue:@""];
	[altitudeField setStringValue:@""];
	[timeField setStringValue:@""];
	[headingField setStringValue:@""];
	[speedField setStringValue:@""];
	[gpsBox setHidden:TRUE];
	
	[pictureBox setImage:nil];
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 191;
	frame.origin.y += heightChange;
	frame.size.height -= heightChange;
	[mainWindow setMinSize:frame.size];
	[mainWindow setFrame:frame display:YES animate:NO];
}

- (void)PositionFixStatusChange:(NSNumber *)positionFixStatus
{
	[fixStatus setState:[positionFixStatus intValue]];
}

- (void)PositionChange:(NSArray *)positionChangeData
{
	double speed, heading;
	GPSTime time;
	GPSDate date;
	
	[latitudeField setStringValue:[NSString stringWithFormat:@"%0.6f°",[[positionChangeData objectAtIndex:0] doubleValue]]];
	[longitudeField setStringValue:[NSString stringWithFormat:@"%0.6f°",[[positionChangeData objectAtIndex:1] doubleValue]]];
	[altitudeField setStringValue:[NSString stringWithFormat:@"%0.1fm",[[positionChangeData objectAtIndex:2] doubleValue]]];
	
	if(!CPhidgetGPS_getVelocity(gps, &speed))
	{
		[speedField setStringValue:[NSString stringWithFormat:@"%0.2fkm/h",speed]];
	}
	
	if(!CPhidgetGPS_getHeading(gps, &heading))
	{
		[headingField setStringValue:[NSString stringWithFormat:@"%0.1f°",heading]];
	}
	
	if(!CPhidgetGPS_getTime(gps, &time) && !CPhidgetGPS_getDate(gps, &date))
	{
		[timeField setTitleWithMnemonic:[NSString stringWithFormat:@"%02d:%02d:%02d   %02d/%02d/%02d",
									 time.tm_hour,time.tm_min,time.tm_sec,date.tm_mday,date.tm_mon,date.tm_year]];
	}
}


/*
* 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 = [[args objectAtIndex:[args count]-1] intValue];
		if(serial == 0) serial = -1;
	}
	
	[mainWindow setDelegate:self];
	
	CPhidget_enableLogging(PHIDGET_LOG_INFO, NULL);
	
	CPhidgetGPS_create(&gps);
	
	CPhidget_set_OnAttach_Handler((CPhidgetHandle)gps, gotAttach, self);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)gps, gotDetach, self);
	CPhidgetGPS_set_OnPositionFixStatusChange_Handler(gps, gotPositionFixStatusChange, self);
	CPhidgetGPS_set_OnPositionChange_Handler(gps, gotPositionChange, self);
	
	if(remote)
		CPhidget_openRemote((CPhidgetHandle)gps, serial, NULL, NULL);
	else
		CPhidget_open((CPhidgetHandle)gps, serial);
}

- (void)windowWillClose:(NSNotification *)aNotification {
	//Because this event is called twice
	if(gps)
	{
		//Stop all events before closing
		CPhidget_set_OnAttach_Handler((CPhidgetHandle)gps, NULL, NULL);
		CPhidget_set_OnDetach_Handler((CPhidgetHandle)gps, NULL, NULL);
		CPhidgetGPS_set_OnPositionFixStatusChange_Handler(gps, NULL, NULL);
		CPhidgetGPS_set_OnPositionChange_Handler(gps, NULL, NULL);
		
		CPhidget_close((CPhidgetHandle)gps);
		CPhidget_delete((CPhidgetHandle)gps);
		gps = NULL;
	}
	[NSApp terminate:self];
}@end
