#import "PhidgetTextLCDController.h"

CPhidgetTextLCDHandle lcd;

@implementation PhidgetTextLCDController

- (IBAction)contrastChanged:(id)sender
{
	CPhidgetTextLCD_setContrast(lcd,[sender intValue]);
	[contrastField setIntValue:[sender intValue]];
}

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

- (IBAction)backlightChecked:(id)sender
{
	CPhidgetTextLCD_setBacklight(lcd,[sender state]);
}
- (IBAction)cursorChecked:(id)sender
{
	CPhidgetTextLCD_setCursorOn(lcd,[sender state]);
}
- (IBAction)cursorBlinkChecked:(id)sender
{
	CPhidgetTextLCD_setCursorBlink(lcd,[sender state]);
}

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

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

int gotSleep(void *context) {
	CPhidgetTextLCD_setDisplayString(lcd,0,"System Sleep.");
	return 0;
}

int gotWakeup(void *context) {
	CPhidgetTextLCD_setDisplayString(lcd,0,"System Wakeup.");
	return 0;
}

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

	CPhidget_getSerialNumber((CPhidgetHandle)lcd, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)lcd, &version);
	CPhidget_getDeviceName((CPhidgetHandle)lcd, &name);
	CPhidget_getDeviceID((CPhidgetHandle)lcd, &devid);
	CPhidgetTextLCD_getRowCount(lcd, &numRows);
	CPhidgetTextLCD_getColumnCount(lcd, &numCols);
	
	[connectedField setStringValue:[NSString stringWithCString:name]];
	[serialField setIntValue:serial];
	[versionField setIntValue:version];
	[numRowsField setIntValue:numRows];
	[numColsField setIntValue:numCols];
	
	[cursorCheck setState:0];
	[cursorBlinkCheck setState:0];
	
	[settingsBox setHidden:FALSE];
	[displayBox setHidden:FALSE];
	
	NSSize size = [settingsBox frame].size;
	NSRect frame2 = [settingsBox frame];
	switch(devid)
	{
		case PHIDID_TEXTLCD_2x20_w_8_8_8:
			//This version has backlight defaulted to off, and supports backlight brightness
			if(version >= 200)
			{
				heightChange = frame.size.height - 410;
				size.height = 97;
				frame2.origin.y = frame2.origin.y + frame2.size.height - 97;
				frame2.size.height = 97;
				[backlightCheck setState:0];
				[brightnessLabel setHidden:FALSE];
				[brightnessField setHidden:FALSE];
				[brightnessSlider setHidden:FALSE];
				break;
			}
		default:
			heightChange = frame.size.height - 389;
			size.height = 76;
			frame2.origin.y = frame2.origin.y + frame2.size.height - 76;
			frame2.size.height = 76;
			[backlightCheck setState:1];
			[brightnessLabel setHidden:TRUE];
			[brightnessField setHidden:TRUE];
			[brightnessSlider setHidden:TRUE];
	}
	[settingsBox setFrame:frame2];
	[settingsBox setFrameSize:size];
	
	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
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[connectedField setStringValue:@"Nothing"];
	[serialField setStringValue:@""];
	[versionField setStringValue:@""];
	[row1Box setStringValue:@""];
	[row2Box 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];
}

/*
* 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;
	}
	
	[row1Box setFont:[NSFont fontWithName:@"Courier New" size:14.0]];
	[row2Box setFont:[NSFont fontWithName:@"Courier New" size:14.0]];
	
	[mainWindow setDelegate:self];
	[row1Box setDelegate:self];
	[row2Box setDelegate:self];
	
	CPhidgetTextLCD_create(&lcd);
	
	CPhidget_set_OnAttach_Handler((CPhidgetHandle)lcd, gotAttach, self);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)lcd, gotDetach, self);
	
	CPhidget_set_OnWillSleep_Handler(gotSleep, self);
	CPhidget_set_OnWakeup_Handler(gotWakeup, self);
	
	if(remote)
		CPhidget_openRemote((CPhidgetHandle)lcd, serial, NULL, NULL);
	else
		CPhidget_open((CPhidgetHandle)lcd, serial);
}

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

- (void)controlTextDidChange:(NSNotification *)aNotification
{
	if([[[aNotification object]  stringValue] length] > 20)
		[[aNotification object] setStringValue:[[[aNotification object]  stringValue] substringToIndex:20]];
	
	if ([aNotification object] == row1Box)
		CPhidgetTextLCD_setDisplayString(lcd,0,(char *)[[row1Box  stringValue] UTF8String]);
	if ([aNotification object] == row2Box)
		CPhidgetTextLCD_setDisplayString(lcd,1,(char *)[[row2Box  stringValue] UTF8String]);
}

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