#import "PhidgetAnalogController.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;
}

@implementation PhidgetAnalogController

- (IBAction)setVoltage:(id)sender
{
	CPhidgetAnalog_setVoltage(analog, [sender selectedTag], [[sender cellWithTag:[sender selectedTag]] doubleValue]);
	[[outputValues cellWithTag:[sender selectedTag]] setStringValue:[NSString stringWithFormat:@"%0.1lfV",[[sender cellWithTag:[sender selectedTag]] doubleValue]]];
}

- (IBAction)setOutputEnabled:(id)sender
{
	CPhidgetAnalog_setEnabled(analog, [sender selectedTag], [[sender cellWithTag:[sender selectedTag]] state]);
}

- (void)phidgetAdded:(id)nothing
{
	int serial, version, i;
	const char *name;
	CPhidget_DeviceID devid;
	double outMax, outMin;

	CPhidget_getSerialNumber((CPhidgetHandle)analog, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)analog, &version);
	CPhidget_getDeviceName((CPhidgetHandle)analog, &name);
	CPhidget_getDeviceID((CPhidgetHandle)analog, &devid);
	CPhidgetAnalog_getOutputCount(analog,&numOutputs);
	CPhidgetAnalog_getVoltageMax(analog, 0, &outMax);
	CPhidgetAnalog_getVoltageMin(analog, 0, &outMin);
	
	//numOutputs = 1;
	
	[connectedField setStringValue:[NSString stringWithCString:name]];
	[serialField setIntValue:serial];
	[versionField setIntValue:version];
	[numOutputsField setIntValue:numOutputs];
	
	if(outMax == -outMin)
		[outputRangeField setStringValue:[NSString stringWithFormat:@"+-%0.1lfV",outMax]];
	else
		[outputRangeField setStringValue:[NSString stringWithFormat:@"%0.1lfV to %0.1lfV",outMin,outMax]];
	
	[outputLabels renewRows:numOutputs columns:1];
	[outputsEnabled renewRows:numOutputs columns:1];
	[outputSliders renewRows:numOutputs columns:1];
	[outputValues renewRows:numOutputs columns:1];
	for(i=0;i<numOutputs;i++)
	{
		int state;
		double val;
		
		CPhidgetAnalog_getEnabled(analog, i, &state);
		[[outputsEnabled cellWithTag:i] setEnabled:TRUE];
		[[outputsEnabled cellWithTag:i] setState:state];
		
		CPhidgetAnalog_getVoltage(analog, i, &val);
		[[outputValues cellWithTag:i] setStringValue:[NSString stringWithFormat:@"%0.1lfV",val]];
		
		CPhidgetAnalog_getVoltageMax(analog, i, &outMax);
		CPhidgetAnalog_getVoltageMin(analog, i, &outMin);
		[[outputSliders cellWithTag:i] setMinValue:outMin];
		[[outputSliders cellWithTag:i] setMaxValue:outMax];
		[[outputSliders cellWithTag:i] setEnabled:TRUE];
		[[outputSliders cellWithTag:i] setDoubleValue:val];
	}
	
	NSRect frame = [outputsBox frame];
	frame.origin.y = frame.origin.y + frame.size.height - (62+19*numOutputs);
	frame.size.height = 62+19*numOutputs;
	[outputsBox setFrame:frame];
	
	NSSize size = [outputsEnabled frame].size;
	size.height = 19*numOutputs;
	[outputsEnabled setFrameSize:size];
	
	size = [outputLabels frame].size;
	size.height = 19*numOutputs;
	[outputLabels setFrameSize:size];
	
	size = [outputSliders frame].size;
	size.height = 19*numOutputs;
	[outputSliders setFrameSize:size];
	
	size = [outputValues frame].size;
	size.height = 19*numOutputs;
	[outputValues setFrameSize:size];
	
	[outputsBox setHidden:FALSE];	
	
	frame = [mainWindow frame];
	int heightChange = frame.size.height - (267 + numOutputs * 19);
	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:@""];
	[numOutputsField setStringValue:@""];
	[outputRangeField setStringValue:@""];
	
	[outputsBox 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];
}

/*
* 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];
	
	CPhidgetAnalog_create(&analog);
	
	CPhidget_set_OnAttach_Handler((CPhidgetHandle)analog, gotAttach, self);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)analog, gotDetach, self);
	
	if(remote)
		CPhidget_openRemote((CPhidgetHandle)analog, serial, NULL, NULL);
	else
		CPhidget_open((CPhidgetHandle)analog, serial);
}

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

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