#import "PhidgetLEDControllers.h"

CPhidgetLEDHandle led;

int lastLED=-1;

@implementation PhidgetLEDControllers

- (IBAction)out:(id)sender
{
	int index = 0;
	index = strtol([[sender title] UTF8String],NULL,10);
	if([sender state]) {
		CPhidgetLED_setDiscreteLED(led, index, [brightnessSlider intValue]);
		lastLED=index;
	}
	else {
		CPhidgetLED_setDiscreteLED(led, index, 0);
		lastLED=-1;
	}
}

- (IBAction)slide:(id)sender
{
	if(lastLED!=-1)
		CPhidgetLED_setDiscreteLED(led, lastLED, [brightnessSlider intValue]);
}

- (IBAction)setVoltage:(id)sender
{
	if([[sender titleOfSelectedItem] isEqualToString:@"1.7V"])
		CPhidgetLED_setVoltage(led, PHIDGET_LED_VOLTAGE_1_7V);
	else if([[sender titleOfSelectedItem] isEqualToString:@"2.75V"])
		CPhidgetLED_setVoltage(led, PHIDGET_LED_VOLTAGE_2_75V);
	else if([[sender titleOfSelectedItem] isEqualToString:@"3.9V"])
		CPhidgetLED_setVoltage(led, PHIDGET_LED_VOLTAGE_3_9V);
	else if([[sender titleOfSelectedItem] isEqualToString:@"5.0V"])
		CPhidgetLED_setVoltage(led, PHIDGET_LED_VOLTAGE_5_0V);
}

- (IBAction)setCurrentLimit:(id)sender
{
	if([[sender titleOfSelectedItem] isEqualToString:@"20mA"])
		CPhidgetLED_setCurrentLimit(led, PHIDGET_LED_CURRENT_LIMIT_20mA);
	else if([[sender titleOfSelectedItem] isEqualToString:@"40mA"])
		CPhidgetLED_setCurrentLimit(led, PHIDGET_LED_CURRENT_LIMIT_40mA);
	else if([[sender titleOfSelectedItem] isEqualToString:@"60mA"])
		CPhidgetLED_setCurrentLimit(led, PHIDGET_LED_CURRENT_LIMIT_60mA);
	else if([[sender titleOfSelectedItem] isEqualToString:@"80mA"])
		CPhidgetLED_setCurrentLimit(led, PHIDGET_LED_CURRENT_LIMIT_80mA);
}

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

- (void)phidgetAdded:(id)nothing
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	int serial, version;
	int numLEDs;
	const char *name;
	CPhidget_DeviceID devid;

	CPhidget_getSerialNumber((CPhidgetHandle)led, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)led, &version);
	CPhidget_getDeviceName((CPhidgetHandle)led, &name);
	CPhidget_getDeviceID((CPhidgetHandle)led, &devid);
	CPhidgetLED_getLEDCount(led,&numLEDs);
	
	[connectedField setStringValue:[NSString stringWithCString:name]];
	[serialField setIntValue:serial];
	[versionField setIntValue:version];
	[numLEDsField setIntValue:numLEDs];
	
	[ledsBox setHidden:FALSE];
	
	NSRect frame = [mainWindow frame];
	int heightChange;
	switch(devid)
	{
		case PHIDID_LED_64_ADV:
		{
			CPhidgetLED_Voltage voltage;
			CPhidgetLED_CurrentLimit currentLimit;
			CPhidgetLED_getVoltage(led, &voltage);
			CPhidgetLED_getCurrentLimit(led, &currentLimit);
			[currentVoltageBox setHidden:FALSE];
			heightChange = frame.size.height - 468;
			[voltageCombo selectItemAtIndex:voltage-1];
			[currentLimitCombo selectItemAtIndex:currentLimit-1];
		}
			break;
		case PHIDID_LED_64:
		default:
			heightChange = frame.size.height - 416;
			break;
	}
	
	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:(id)nothing
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[connectedField setTitleWithMnemonic:@"Nothing"];
	[serialField setTitleWithMnemonic:@""];
	[versionField setTitleWithMnemonic:@""];
	[numLEDsField setTitleWithMnemonic:@""];
	
	[ledsBox setHidden:TRUE];
	[currentVoltageBox setHidden:TRUE];
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 190;
	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];
}

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

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

- (void)setPicture:(int)version:(CPhidget_DeviceID)devid
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSString *imgPath;
	
	switch(devid)
	{
		case PHIDID_LED_64:
			imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1030_0" ofType:@"icns"];
			break;
		case PHIDID_LED_64_ADV:
			imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1031_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
