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

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

/*
* This gets run when the GUI gets displayed
*/
- (void)awakeFromNib
{
	[mainWindow setDelegate:self];
	
	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);
	
	[self openCmdLine];
}

- (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);
		CPhidget_set_OnError_Handler((CPhidgetHandle)gps, gotError, self);
		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];
}

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)gps);
			[NSApp runModalForWindow:passwordPanel];
			break;
		case EEPHIDGET_BADVERSION:
			CPhidget_close((CPhidgetHandle)gps);
			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
