#import "PhidgetEncoderController.h"

CPhidgetEncoderHandle encoder;

@implementation PhidgetEncoderController

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

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

int gotInputChange(CPhidgetEncoderHandle phid, void *context, int ind, int val) {
	[(id)context EncoderInputChange:ind:val];
	return 0;
}

int gotPositionChange(CPhidgetEncoderHandle phid, void *context, int ind, int time, int dir) {
	int position;
	CPhidgetEncoder_getPosition(encoder, ind, &position);
	[(id)context EncoderPositionChange:ind:position:time];
	return 0;
}

- (void)phidgetAdded
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	int serial, version;
	int numEncoders, numInputs;
	const char *name;
	CPhidget_DeviceID devid;
	
	CPhidget_getSerialNumber((CPhidgetHandle)encoder, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)encoder, &version);
	CPhidget_getDeviceName((CPhidgetHandle)encoder, &name);
	CPhidget_getDeviceID((CPhidgetHandle)encoder, &devid);
	CPhidgetEncoder_getInputCount(encoder, &numInputs);
	CPhidgetEncoder_getEncoderCount(encoder, &numEncoders);
	
	[connectedField setStringValue:[NSString stringWithCString:name]];
	[serialField setIntValue:serial];
	[versionField setIntValue:version];
	[numEncodersField setIntValue:numEncoders];
	[numInputsField setIntValue:numInputs];
	
	switch(devid)
	{
		case PHIDID_ENCODER_1ENCODER_1INPUT:
			[positionSlider setMaxValue:250];
			[positionSlider setMinValue:-250];
			[inputCheckBox setHidden:FALSE];
			break;
		case PHIDID_ENCODER_HS_1ENCODER:
			[positionSlider setMaxValue:50000];
			[positionSlider setMinValue:-50000];
			[inputCheckBox setHidden:TRUE];
			break;
		default:
			break;
	}
	
	[encoderBox setHidden:FALSE];
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 273;
	if (numInputs == 1)
		heightChange = frame.size.height - 302;
	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 setTitleWithMnemonic:@"Nothing"];
	[serialField setTitleWithMnemonic:@""];
	[versionField setTitleWithMnemonic:@""];
	[numInputsField setTitleWithMnemonic:@""];
	[numEncodersField setTitleWithMnemonic:@""];
	
	[encoderBox setHidden:TRUE];
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 192;
	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)EncoderInputChange:(int)Index:(int)State
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	[inputCheckBox setState:State];
	
	[pool release];
}

/* position change */
- (void)EncoderPositionChange:(int)Index:(int)Position:(int)Time
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

	[positionField setIntValue:Position];
	[timeField setIntValue:Time];
	[positionSlider setIntValue:Position];	[pool release];
}

/*
* 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];
	
	
	CPhidgetEncoder_create(&encoder);
	
	CPhidget_set_OnAttach_Handler((CPhidgetHandle)encoder, gotAttach, self);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)encoder, gotDetach, self);
	CPhidgetEncoder_set_OnInputChange_Handler(encoder, gotInputChange, self);
	CPhidgetEncoder_set_OnPositionChange_Handler(encoder, gotPositionChange, self);
	
	if(remote)
		CPhidget_openRemote((CPhidgetHandle)encoder, serial, NULL, NULL);
	else
		CPhidget_open((CPhidgetHandle)encoder, serial);
}

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

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