#import "PhidgetPHSensorController.h"

CPhidgetPHSensorHandle ph;

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 gotPH(CPhidgetPHSensorHandle phid, void *context, double val) {
	[(id)context gotPHChange:val];
	return 0;
}

@implementation PhidgetPHSensorController

- (void)gotPHChange:(double)val
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	double potential;
	[phField setTitleWithMnemonic:[NSString stringWithFormat:@"%0.4f",val]];
	CPhidgetPHSensor_getPotential(ph, &potential);
	[potentialField setTitleWithMnemonic:[NSString stringWithFormat:@"%0.4f",potential]];
	[pool release];
}

- (IBAction)setChangeTrigger:(id)sender
{
	CPhidgetPHSensor_setPHChangeTrigger(ph, [triggerField floatValue]);
}

- (IBAction)setTemperature:(id)sender
{
	CPhidgetPHSensor_setTemperature(ph, [temperatureField floatValue]);
}

- (void)phidgetAdded
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	int serial, version;
	double trigger;
	const char *name;
	CPhidget_DeviceID devid;
	double phMax, phMin, potMax, potMin;
	
	CPhidgetPHSensor_setPHChangeTrigger(ph, 0.05);

	CPhidget_getSerialNumber((CPhidgetHandle)ph, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)ph, &version);
	CPhidget_getDeviceName((CPhidgetHandle)ph, &name);
	CPhidget_getDeviceID((CPhidgetHandle)ph, &devid);
	CPhidgetPHSensor_getPHChangeTrigger(ph, &trigger);
	CPhidgetPHSensor_getPHMax(ph, &phMax);
	CPhidgetPHSensor_getPHMin(ph, &phMin);
	CPhidgetPHSensor_getPotentialMax(ph, &potMax);
	CPhidgetPHSensor_getPotentialMin(ph, &potMin);
	
	[connectedField setStringValue:[NSString stringWithCString:name]];
	[serialField setIntValue:serial];
	[versionField setIntValue:version];
	[triggerField setStringValue:[NSString stringWithFormat:@"%0.2f",trigger]];
	[phRangeField setStringValue:[NSString stringWithFormat:@"%0.2f - %0.2f",phMin,phMax]];
	[potentialRangeField setStringValue:[NSString stringWithFormat:@"%0.0fmV - %0.0fmV",potMin,potMax]];
	
	[sensorBox setHidden:FALSE];
	[settingsBox setHidden:FALSE];
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 363;
	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:@""];
	[phField setStringValue:@""];
	[potentialField setStringValue:@""];
	[triggerField setStringValue:@""];
	[temperatureField setStringValue:@""];
	[phRangeField setStringValue:@""];
	[potentialRangeField setStringValue:@""];
	
	[sensorBox setHidden:TRUE];
	[settingsBox 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];
}

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

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

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

- (void)setPicture:(int)version:(CPhidget_DeviceID)devid
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSString *imgPath;
	
	switch(devid)
	{
		case PHIDID_PHSENSOR:
			imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1058_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)ph);
			[NSApp runModalForWindow:passwordPanel];
			break;
		case EEPHIDGET_BADVERSION:
			CPhidget_close((CPhidgetHandle)ph);
			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
