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

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 stringWithUTF8String:error], nil]
							   waitUntilDone:NO];
	[pool release];
	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 stringWithUTF8String: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];
}

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

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

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

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