#import "PhidgetInterfaceKitController.h"

CPhidgetInterfaceKitHandle ifkit;
int numOutputs, numInputs, numSensors;

@implementation PhidgetInterfaceKitController

int gotAttach(CPhidgetHandle phid, void *context) {
	[(id)context phidgetAdded];
	return 0;
}

int gotDetach(CPhidgetHandle phid, void *context) {
	[(id)context phidgetRemoved];
	return 0;
}

int gotInputChange(CPhidgetInterfaceKitHandle phid, void *context, int ind, int val) {
	[(id)context InputChange:ind:val];
	return 0;
}

int gotSensorChange(CPhidgetInterfaceKitHandle phid, void *context, int ind, int val) {
	[(id)context SensorChange:ind:val];
	return 0;
}

int gotOutputChange(CPhidgetInterfaceKitHandle phid, void *context, int ind, int val) {
	[(id)context OutputChange:ind:val];
	return 0;
}

- (void)setPicture:(int)version:(const char *)name
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSString *imgPath;
	
	if (!strcmp(name, "Phidget InterfaceKit 8/8/8")) 
	{
		if(version > 800 && version < 824)
			imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1013_0" ofType:@"icns"];
		else if(version < 200)
			imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1200_1" ofType:@"icns"];
		else
			imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1018_0" ofType:@"icns"];
	}
	else if (!strcmp(name, "Phidget InterfaceKit 0/0/4")) 
	{
		imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1014_0" ofType:@"icns"];
	}
	else if (!strcmp(name, "Phidget InterfaceKit 0/16/16")) 
	{
		imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1012_0" ofType:@"icns"];
	}
	else if (!strcmp(name, "Phidget Touch Slider")) 
	{
		imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1015_0" ofType:@"icns"];
	}
	else if (!strcmp(name, "Phidget Touch Rotation")) 
	{
		imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1016_0" ofType:@"icns"];
	}
	else if (!strcmp(name, "Phidget InterfaceKit 0/0/8")) 
	{
		imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1017_0" ofType:@"icns"];
	}
	else imgPath = nil;
	
	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];
}

- (void)phidgetAdded
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	int serial, version, i;
	int ratio, sensitivity;
	int ret;
	const char *name;
	
	CPhidget_getSerialNumber((CPhidgetHandle)ifkit, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)ifkit, &version);
	CPhidget_getDeviceName((CPhidgetHandle)ifkit, &name);
	CPhidgetInterfaceKit_getSensorCount(ifkit, &numSensors);
	CPhidgetInterfaceKit_getInputCount(ifkit, &numInputs);
	CPhidgetInterfaceKit_getOutputCount(ifkit, &numOutputs);
	
	[connectedField setStringValue:[NSString stringWithCString:name]];
	[serialField setIntValue:serial];
	[versionField setIntValue:version];
	[numOutputsField setIntValue:numOutputs];
	[numInputsField setIntValue:numInputs];
	[numSensorsField setIntValue:numSensors];
		
	if(numInputs)
	{
		[inputs renewRows:numInputs columns:1];
		[inputLabels renewRows:numInputs columns:1];
		for(i=0;i<numInputs;i++)
		{
			[[inputs cellWithTag:i] setEnabled:FALSE];
			[[inputs cellWithTag:i] setState:FALSE];
		}
		NSRect frame = [inputsBox frame];
		frame.origin.y = frame.origin.y + frame.size.height - (35+19*numInputs);
		frame.size.height = 35+19*numInputs;
		NSSize size = [inputs frame].size;
		size.height = 19*numInputs;
		[inputs setFrameSize:size];
		size = [inputLabels frame].size;
		size.height = 19*numInputs;
		[inputLabels setFrameSize:size];
		[inputsBox setFrame:frame];
		[inputsBox setHidden:FALSE];
	}
	
	if(numOutputs)
	{
		[outputs renewRows:numOutputs columns:1];
		[outputLabels renewRows:numOutputs columns:1];
		for(i=0;i<numOutputs;i++)
		{
			[[outputs cellWithTag:i] setEnabled:TRUE];
			[[outputs cellWithTag:i] setState:FALSE];
		}
		NSRect frame = [outputsBox frame];
		frame.origin.y = frame.origin.y + frame.size.height - (35+19*numOutputs);
		frame.size.height = 35+19*numOutputs;
		NSSize size = [outputs frame].size;
		size.height = 19*numOutputs;
		[outputs setFrameSize:size];
		size = [outputLabels frame].size;
		size.height = 19*numOutputs;
		[outputLabels setFrameSize:size];
		[outputsBox setFrame:frame];
		[outputsBox setHidden:FALSE];
	}
	
	if(numSensors)
	{
		[sensorSliders renewRows:numSensors columns:1];
		[sensorFields renewRows:numSensors columns:1];
		[sensorLabels renewRows:numSensors columns:1];
		for(i=0;i<numSensors;i++)
		{
			[[sensorSliders cellWithTag:i] setIntValue:0];
			[[sensorFields cellWithTag:i] setStringValue:@""];
			[[sensorSliders cellWithTag:i] setEnabled:TRUE];
		}
		
		if(!(ret = CPhidgetInterfaceKit_getRatiometric(ifkit, &ratio)))
		{
			if(ratio==0 || ratio==1)
			{
				[ratiometric setState:ratio];
			}
		}
		if(ret != EPHIDGET_UNSUPPORTED)
			[ratiometric setEnabled:TRUE];
		
		if(!(ret = CPhidgetInterfaceKit_getSensorChangeTrigger(ifkit, 0, &sensitivity)))
		{
			[sensitivityField setIntValue:sensitivity];
			[sensitivitySlider setIntValue:sensitivity];
		}
		if(ret != EPHIDGET_UNSUPPORTED)
			[sensitivitySlider setEnabled:TRUE];
		
		NSRect frame = [sensorsBox frame];
		frame.origin.y = frame.origin.y + frame.size.height - (123+19*numSensors);
		frame.size.height = 123+19*numSensors;
		NSSize size = [sensorSliders frame].size;
		size.height = 19*numSensors;
		[sensorSliders setFrameSize:size];
		size = [sensorLabels frame].size;
		size.height = 20*numSensors;
		[sensorLabels setFrameSize:size];
		size = [sensorFields frame].size;
		size.height = 20*numSensors;
		[sensorFields setFrameSize:size];
		[sensorsBox setFrame:frame];
		
		[sensorsBox setHidden:FALSE];
	}
	
	NSRect frame = [mainWindow frame];
	int heightChange = 0;
	if(numInputs == 16)
		heightChange = frame.size.height - 546;
	else if(numSensors == 8)
		heightChange = frame.size.height - 482;
	else if(numOutputs == 8)
		heightChange = frame.size.height - 394;
	else if(numOutputs == 4)
		heightChange = frame.size.height - 318;
	else if(numSensors == 1)
		heightChange = frame.size.height - 349;
		
	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:name];

	[pool release];
	
	[mainWindow display];
}

- (void)phidgetRemoved
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	[connectedField setStringValue:@"Nothing"];
	[serialField setStringValue:@""];
	[versionField setStringValue:@""];
	[numInputsField setStringValue:@""];
	[numOutputsField setStringValue:@""];
	[numSensorsField setStringValue:@""];
	
	[inputsBox setHidden:TRUE];
	[outputsBox setHidden:TRUE];
	[sensorsBox setHidden:TRUE];
	
	[ratiometric setEnabled:FALSE];
	[sensitivityField setStringValue:@""];
	[sensitivitySlider setIntValue:0];
	[sensitivitySlider setEnabled:FALSE];
		
	[self setPicture:0:""];
	[mainWindow display];
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 203;
	frame.origin.y += heightChange;
	frame.size.height -= heightChange;
	[mainWindow setMinSize:frame.size];
	[mainWindow setFrame:frame display:YES animate:NO];
	
	[pool release];
	
	[mainWindow display];
}

- (void)OutputChange:(int)Index:(int)State
{
	[[outputs cellWithTag:Index] setState:State];
}

- (void)InputChange:(int)Index:(int)State
{
	[[inputs cellWithTag:Index] setState:State];
}

- (void)SensorChange:(int)Index:(int)Value
{
	int rawVal;
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	[[sensorFields cellWithTag:Index] setIntValue:Value];
	[[sensorSliders cellWithTag:Index] setIntValue:Value];
	
	CPhidgetInterfaceKit_getSensorRawValue(ifkit, Index, &rawVal);
	
	[pool release];
}

- (IBAction)output:(id)sender
{
	CPhidgetInterfaceKit_setOutputState(ifkit, [sender selectedTag], [[sender cellWithTag:[sender selectedTag]] state]);
}

- (IBAction)ratiometric:(id)sender
{
	CPhidgetInterfaceKit_setRatiometric(ifkit, [sender state]);
}

- (IBAction)sensitivity:(id)sender
{
	int i;
	for(i=0;i<numSensors;i++)
		CPhidgetInterfaceKit_setSensorChangeTrigger(ifkit, i, [sender intValue]);
	[sensitivityField setIntValue:[sender intValue]];
}

/*
* 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];
	
	CPhidget_enableLogging(PHIDGET_LOG_VERBOSE, NULL);
	
	CPhidgetInterfaceKit_create(&ifkit);
	
	CPhidget_set_OnAttach_Handler((CPhidgetHandle)ifkit, gotAttach, self);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)ifkit, gotDetach, self);
	CPhidgetInterfaceKit_set_OnInputChange_Handler(ifkit, gotInputChange, self);
	CPhidgetInterfaceKit_set_OnSensorChange_Handler(ifkit, gotSensorChange, self);
	CPhidgetInterfaceKit_set_OnOutputChange_Handler(ifkit, gotOutputChange, self);
	
	if(remote)
		CPhidget_openRemote((CPhidgetHandle)ifkit, serial, NULL, NULL);
	else
		CPhidget_open((CPhidgetHandle)ifkit, serial);
}

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

@end
