#import "PhidgetLEDControllers.h"

CPhidgetLEDHandle led;

int lastLED=-1;

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 PhidgetLEDControllers

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

- (IBAction)slide:(id)sender
{
	if(lastLED!=-1)
		CPhidgetLED_setBrightness(led, lastLED, [brightnessSlider doubleValue]);
}
- (IBAction)setCurrentLimitIndexed:(id)sender
{
	if(lastLED!=-1)
		CPhidgetLED_setCurrentLimitIndexed(led, lastLED, [currentLimitSlider doubleValue]);
}

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

- (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 stringWithUTF8String: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 - 489;
			[voltageCombo selectItemAtIndex:voltage-1];
			[currentLimitCombo selectItemAtIndex:currentLimit-1];
			if(version >= 200)
			{
				[currentLimitIndexedLabel setHidden:FALSE];
				[currentLimitSlider setHidden:FALSE];
			}
			break;
		}
		case PHIDID_LED_64:
		default:
			heightChange = frame.size.height - 439;
			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 setStringValue:@"Nothing"];
	[serialField setStringValue:@""];
	[versionField setStringValue:@""];
	[numLEDsField setStringValue:@""];
	
	[ledsBox setHidden:TRUE];
	[currentVoltageBox setHidden:TRUE];
	[currentLimitIndexedLabel setHidden:TRUE];
	[currentLimitSlider 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];
}

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

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

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

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