#import "PhidgetBridgeController.h"

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 gotBridgeData(CPhidgetBridgeHandle phid, void *context, int ind, double val) {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[(id)context performSelectorOnMainThread:@selector(BridgeData:)
								  withObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:ind], [NSNumber numberWithDouble:val], nil]
							   waitUntilDone:NO];
	[pool release];
	return 0;
}

@implementation PhidgetBridgeController

- (void)setRange:(int)index
{
	double maxVal, minVal;
	if(!CPhidgetBridge_getBridgeMax(bridge, index, &maxVal) && !CPhidgetBridge_getBridgeMin(bridge, index, &minVal))
	{
		[[valueSliders cellWithTag:index] setMinValue:minVal];
		[[valueSliders cellWithTag:index] setMaxValue:maxVal];
		if(-minVal == maxVal)
			[[rangeFields cellWithTag:index] setStringValue:[NSString stringWithFormat:@"+-%0.4lf",maxVal]];
		else
			[[rangeFields cellWithTag:index] setStringValue:[NSString stringWithFormat:@"%0.4lf - %0.4lf",minVal, maxVal]];
	}
}

- (IBAction)setInputEnabled:(id)sender
{
	CPhidgetBridge_setEnabled(bridge, [sender selectedTag], [[sender cellWithTag:[sender selectedTag]] state]);
}

- (IBAction)setGain:(id)sender
{
	CPhidgetBridge_setGain(bridge, [sender selectedTag], [[sender cellWithTag:[sender selectedTag]] indexOfSelectedItem]+1);

}

- (IBAction)setDataRate:(id)sender
{
	CPhidgetBridge_setDataRate(bridge, [sender intValue]*8);
	[dataRateField setIntValue:[sender intValue]*8];
}

- (void)phidgetAdded:(id)nothing
{
	int serial, version, i;
	const char *name;
	CPhidget_DeviceID devid;
	int dataRate, dataRateMax, dataRateMin;

	CPhidget_getSerialNumber((CPhidgetHandle)bridge, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)bridge, &version);
	CPhidget_getDeviceName((CPhidgetHandle)bridge, &name);
	CPhidget_getDeviceID((CPhidgetHandle)bridge, &devid);
	CPhidgetBridge_getInputCount(bridge, &numInputs);
	CPhidgetBridge_getDataRateMax(bridge, &dataRateMax);
	CPhidgetBridge_getDataRateMin(bridge, &dataRateMin);
	
	[connectedField setStringValue:[NSString stringWithCString:name]];
	[serialField setIntValue:serial];
	[versionField setIntValue:version];
	[numInputsField setIntValue:numInputs];
	[dataRateSlider setMaxValue:dataRateMin/8];
	[dataRateSlider setMinValue:dataRateMax/8];
	
	if(!CPhidgetBridge_getDataRate(bridge, &dataRate))
	{
		[dataRateSlider setIntValue:dataRate/8];
		[dataRateField setIntValue:dataRate];
	}
	
	for(i=0;i<numInputs;i++)
	{
		int enabledState;
		CPhidgetBridge_Gain gain;
		double value;
		
		if(!CPhidgetBridge_getEnabled(bridge, i, &enabledState))
		{
			[[enabledChecks cellWithTag:i] setState:enabledState];
		}
		
		[self setRange:i];
		
		if(!CPhidgetBridge_getBridgeValue(bridge, i, &value))
		{
			[[valueSliders cellWithTag:i] setDoubleValue:value];
			[[valueFields cellWithTag:i] setStringValue:[NSString stringWithFormat:@"%0.6lf",value]];
		}
		
		if(!CPhidgetBridge_getGain(bridge, i, &gain))
		{
			[[gainComboBoxes cellWithTag:i] selectItemAtIndex:gain-1];
		}
	}
	
	[inputsBox setHidden:FALSE];	
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 388;
	frame.origin.y += heightChange;
	frame.size.height -= heightChange;
	[mainWindow setMinSize:frame.size];
	[mainWindow setFrame:frame display:YES animate:NO];
	
	[self setPicture:version:devid];
	[mainWindow display];
}

- (void)phidgetRemoved:(id)nothing
{
	[connectedField setStringValue:@"Nothing"];
	[serialField setStringValue:@""];
	[versionField setStringValue:@""];
	[numInputsField setStringValue:@""];
	
	[inputsBox setHidden:TRUE];
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 201;
	frame.origin.y += heightChange;
	frame.size.height -= heightChange;
	[mainWindow setMinSize:frame.size];
	[mainWindow setFrame:frame display:YES animate:NO];
	
	[self setPicture:0:0];
	
	[mainWindow display];
}

- (void)BridgeData:(NSArray *)bridgeData
{
	[self setRange:[[bridgeData objectAtIndex:0] intValue]];
	[[valueFields cellWithTag:[[bridgeData objectAtIndex:0] intValue]] 
	 setDoubleValue:[[bridgeData objectAtIndex:1] doubleValue]];
	[[valueSliders cellWithTag:[[bridgeData objectAtIndex:0] intValue]] 
	 setStringValue:[NSString stringWithFormat:@"%0.6lf",[[bridgeData objectAtIndex:1] doubleValue]]];
}

/*
* 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 = strtol([[args objectAtIndex:[args count]-1] UTF8String], NULL, 10);
		if(serial == 0) serial = -1;
	}
	
	[mainWindow setDelegate:self];
	
	CPhidgetBridge_create(&bridge);
	
	CPhidget_set_OnAttach_Handler((CPhidgetHandle)bridge, gotAttach, self);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)bridge, gotDetach, self);
	CPhidgetBridge_set_OnBridgeData_Handler(bridge, gotBridgeData, self);
	
	if(remote)
		CPhidget_openRemote((CPhidgetHandle)bridge, serial, NULL, NULL);
	else
		CPhidget_open((CPhidgetHandle)bridge, serial);
}

- (void)windowWillClose:(NSNotification *)aNotification {
	//Because this event is called twice
	if(bridge)
	{
		CPhidget_close((CPhidgetHandle)bridge);
		CPhidget_delete((CPhidgetHandle)bridge);
		bridge = NULL;
	}
	[NSApp terminate:self];
}

- (void)setPicture:(int)version:(CPhidget_DeviceID)devid
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSString *imgPath;
	
	switch(devid)
	{
		case PHIDID_BRIDGE_4INPUT:
			imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1046_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];
}
@end