#import "PhidgetTextLEDController.h"

CPhidgetTextLEDHandle led;

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

int gotDetach(CPhidgetHandle phid, void *context) {
	[(id)context phidgetRemoved];
	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 stringWithCString:error], nil]
							   waitUntilDone:NO];
	[pool release];
	return 0;
}

@implementation PhidgetTextLEDController

- (IBAction)brightnessChanged:(id)sender
{
	CPhidgetTextLED_setBrightness(led,[sender intValue]);
	[brightnessField setIntValue:[sender intValue]];
}

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

	CPhidget_getSerialNumber((CPhidgetHandle)led, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)led, &version);
	CPhidget_getDeviceName((CPhidgetHandle)led, &name);
	CPhidget_getDeviceID((CPhidgetHandle)led, &devid);
	CPhidgetTextLED_getRowCount(led, &numRows);
	CPhidgetTextLED_getColumnCount(led, &numCols);
	
	[connectedField setStringValue:[NSString stringWithCString:name]];
	[serialField setIntValue:serial];
	[versionField setIntValue:version];
	[numRowsField setIntValue:numRows];
	[numColsField setIntValue:numCols];
	
	CPhidgetTextLED_setBrightness(led, 100);
	
	switch(devid)
	{
		case PHIDID_TEXTLED_4x8:
			[row2Label setHidden:FALSE];
			[row2Box setHidden:FALSE];
			[row3Label setHidden:FALSE];
			[row3Box setHidden:FALSE];
			[row4Label setHidden:FALSE];
			[row4Box setHidden:FALSE];
			break;
		case PHIDID_TEXTLED_1x8:
			[row2Label setHidden:TRUE];
			[row2Box setHidden:TRUE];
			[row3Label setHidden:TRUE];
			[row3Box setHidden:TRUE];
			[row4Label setHidden:TRUE];
			[row4Box setHidden:TRUE];
			break;
		default:
			break;
	}
	
	[settingsBox setHidden:FALSE];
	[displayBox setHidden:FALSE];
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 367;
	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];
}

/*
* check if it's the servo we've been controlling and if so disable the controls
*/
- (void)phidgetRemoved
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[connectedField setStringValue:@"Nothing"];
	[serialField setStringValue:@""];
	[versionField setStringValue:@""];
	[row1Box setStringValue:@""];
	[row2Box setStringValue:@""];
	[row3Box setStringValue:@""];
	[row4Box setStringValue:@""];
	[numRowsField setStringValue:@""];
	[numColsField setStringValue:@""];
	
	[settingsBox setHidden:TRUE];
	[displayBox setHidden:TRUE];
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 195;
	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];
	[row1Box setDelegate:self];
	[row2Box setDelegate:self];
	[row3Box setDelegate:self];
	[row4Box setDelegate:self];
	
	[row1Box setFont:[NSFont fontWithName:@"Courier New" size:14.0]];
	[row2Box setFont:[NSFont fontWithName:@"Courier New" size:14.0]];
	[row3Box setFont:[NSFont fontWithName:@"Courier New" size:14.0]];
	[row4Box setFont:[NSFont fontWithName:@"Courier New" size:14.0]];
	
	CPhidget_enableLogging(PHIDGET_LOG_VERBOSE, NULL);
	
	CPhidgetTextLED_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)controlTextDidChange:(NSNotification *)aNotification
{
	if([[[aNotification object]  stringValue] length] > 8)
		[[aNotification object] setStringValue:[[[aNotification object]  stringValue] substringToIndex:8]];
	
	if ([aNotification object] == row1Box)
		CPhidgetTextLED_setDisplayString(led,0,(char *)[[row1Box  stringValue] UTF8String]);
	if ([aNotification object] == row2Box)
		CPhidgetTextLED_setDisplayString(led,1,(char *)[[row2Box  stringValue] UTF8String]);
	if ([aNotification object] == row3Box)
		CPhidgetTextLED_setDisplayString(led,2,(char *)[[row3Box  stringValue] UTF8String]);
	if ([aNotification object] == row4Box)
		CPhidgetTextLED_setDisplayString(led,3,(char *)[[row4Box  stringValue] UTF8String]);
}

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