#import "PhidgetStepperController.h"

CPhidgetStepperHandle stepper;
int globalIndex = 0;

@implementation PhidgetStepperController

- (IBAction)setAcceleration:(id)sender
{
	CPhidgetStepper_setAcceleration(stepper, globalIndex, [sender doubleValue]);
	[accelerationSetField setDoubleValue:[sender doubleValue]];
}

- (IBAction)setPosition:(id)sender
{
	CPhidgetStepper_setTargetPosition(stepper, globalIndex, (long long)[sender intValue]);
	[positionSetTextBox setIntValue:[sender intValue]];
}

- (IBAction)setPositionBox:(id)sender
{
	long long posn;
	const char *posnString = [[sender stringValue] UTF8String];
	posn = strtoll(posnString, NULL, 10);
	CPhidgetStepper_setTargetPosition(stepper, globalIndex, posn);
}

- (IBAction)setCurrentPosition:(id)sender
{
	CPhidgetStepper_setCurrentPosition(stepper, globalIndex, (long long)[sender intValue]);
	[currentPositionSetTextBox setIntValue:[sender intValue]];
}

- (IBAction)setEnabled:(id)sender
{
	CPhidgetStepper_setEngaged(stepper, globalIndex, [sender state]);
}

- (IBAction)setCurrentPositionBox:(id)sender
{
	long long posn;
	const char *posnString = [[sender stringValue] UTF8String];
	posn = strtoll(posnString, NULL, 10);
	CPhidgetStepper_setCurrentPosition(stepper, globalIndex, posn);
}

- (IBAction)setStepper:(id)sender
{
	const char *stepperString = [[sender stringValue] UTF8String];
	globalIndex = strtol(stepperString+8, NULL, 10);
	[self fillForm:globalIndex];
}

- (IBAction)setVelocity:(id)sender
{
	CPhidgetStepper_setVelocityLimit(stepper, globalIndex, [sender doubleValue]);
	[velocitySetField setDoubleValue:[sender doubleValue]];
}

- (IBAction)setTorque:(id)sender
{
	CPhidgetStepper_setCurrentLimit(stepper, globalIndex, [sender doubleValue]);
	[torqueSetField setDoubleValue:[sender doubleValue]];
}

int gotPositionChange(CPhidgetStepperHandle phid, void *context, int ind, long long val) {
	[(id)context PositionChange:ind:val];
	return 0;
}

int gotSpeedChange(CPhidgetStepperHandle phid, void *context, int ind, double val) {
	[(id)context SpeedChange:ind:val];
	return 0;
}

int gotCurrentChange(CPhidgetStepperHandle phid, void *context, int ind, double val) {
	[(id)context CurrentChange:ind:val];
	return 0;
}

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

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

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

- (void)phidgetAdded
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	int serial, version;
	const char *name;
	int numInputs, numSteppers;
	int i;
	double maxAccel, minAccel, maxVel, minVel, maxCurrent, minCurrent;
	
	CPhidget_getSerialNumber((CPhidgetHandle)stepper, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)stepper, &version);
	CPhidget_getDeviceName((CPhidgetHandle)stepper, &name);
	CPhidgetStepper_getInputCount(stepper, &numInputs);
	CPhidgetStepper_getMotorCount(stepper, &numSteppers);
	
	[connectedField setTitleWithMnemonic:[NSString stringWithCString:name]];
	[serialField setTitleWithMnemonic:[NSString stringWithFormat:@"%d", serial]];
	[versionField setTitleWithMnemonic:[NSString stringWithFormat:@"%d", version]];
	[numberOfInputsField setTitleWithMnemonic:[NSString stringWithFormat:@"%d", numInputs]];
	[numberOfSteppersField setTitleWithMnemonic:[NSString stringWithFormat:@"%d", numSteppers]];
	
	CPhidgetStepper_getAccelerationMax(stepper, 0, &maxAccel);
	CPhidgetStepper_getAccelerationMin(stepper, 0, &minAccel);
	CPhidgetStepper_getVelocityMax(stepper, 0, &maxVel);
	CPhidgetStepper_getVelocityMin(stepper, 0, &minVel);
	
	if(!strncmp(name+8,"Bipolar",7))
	{
		CPhidgetStepper_getCurrentMax(stepper, 0, &maxCurrent);
		CPhidgetStepper_getCurrentMin(stepper, 0, &minCurrent);
		[currentTrackBar setMaxValue:maxCurrent];
		[currentTrackBar setMinValue:minCurrent];
		[torqueSetTrackBar setMaxValue:maxCurrent];
		[torqueSetTrackBar setMinValue:minCurrent];
	}
	else if(!strncmp(name+8,"Unipolar",8))
	{
	}
	
	[currentPositionSetTrackBar setMaxValue:20000];
	[currentPositionSetTrackBar setMinValue:-20000];
	[positionTrackBar setMaxValue:20000];
	[positionTrackBar setMinValue:-20000];
	[positionSetTrackBar setMaxValue:20000];
	[positionSetTrackBar setMinValue:-20000];
	[velocityTrackBar setMaxValue:maxVel];
	[velocityTrackBar setMinValue:-maxVel];
	[velocitySetTrackBar setMaxValue:maxVel];
	[velocitySetTrackBar setMinValue:minVel];
	[accelerationSetTrackBar setMaxValue:maxAccel];
	[accelerationSetTrackBar setMinValue:minAccel];
	
	for(i=0;i<numSteppers;i++)
	{
		CPhidgetStepper_setCurrentPosition(stepper, i, 0);
		CPhidgetStepper_setAcceleration(stepper, i, maxAccel/2.0);
		CPhidgetStepper_setVelocityLimit(stepper, i, maxVel/2.0);
	}

	[self fillForm:0];
	[pool release];
}

- (void)fillForm:(int)index
{
	long long posn, targetPosn;
	double velocity, velocityLimit;
	double accel, current;
	int stopped, engaged;
	
	CPhidgetStepper_getVelocity(stepper, index, &velocity);
	CPhidgetStepper_getAcceleration(stepper, index, &accel);
	CPhidgetStepper_getVelocityLimit(stepper, index, &velocityLimit);
	CPhidgetStepper_getCurrentPosition(stepper, index, &posn);
	CPhidgetStepper_getTargetPosition(stepper, index, &targetPosn);
	CPhidgetStepper_getEngaged(stepper, index, &engaged);
	CPhidgetStepper_getStopped(stepper, index, &stopped);
	
	if(!CPhidgetStepper_getCurrent(stepper, index, &current))
	{
		[currentField setDoubleValue:current];
		[currentTrackBar setDoubleValue:current];
	}
	
	[velocitySetField setDoubleValue:velocityLimit];
	[velocitySetTrackBar setDoubleValue:velocityLimit];
	[accelerationSetField setDoubleValue:accel];
	[accelerationSetTrackBar setDoubleValue:accel];
	[positionSetTextBox setIntValue:targetPosn];
	[positionSetTrackBar setIntValue:targetPosn];
	
	[positionField setIntValue:posn];
	[positionTrackBar setIntValue:posn];
	[velocityField setDoubleValue:velocity];
	[velocityTrackBar setDoubleValue:velocity];
	
	[stoppedCheckBox setState:stopped];
	[enabledCheckBox setState:engaged];
}

- (void)phidgetRemoved
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	[connectedField setTitleWithMnemonic:@"Nothing"];
	[serialField setTitleWithMnemonic:@""];
	[versionField setTitleWithMnemonic:@""];
	[numberOfInputsField setTitleWithMnemonic:@""];
	[numberOfSteppersField setTitleWithMnemonic:@""];

	[pool release];
}

- (void)PositionChange:(int)Index:(long long)posn
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	int stopped;
	if(globalIndex == Index) {
		[positionField setIntValue:(int)posn];
		[positionTrackBar setIntValue:(int)posn];
		CPhidgetStepper_getStopped(stepper, Index, &stopped);
		[stoppedCheckBox setState:stopped];
	}
	[pool release];
}

- (void)SpeedChange:(int)Index:(double)speed
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	int stopped;
	if(globalIndex == Index) {
		[velocityField setDoubleValue:speed];
		[velocityTrackBar setDoubleValue:speed];
		CPhidgetStepper_getStopped(stepper, Index, &stopped);
		[stoppedCheckBox setState:stopped];
	}
	[pool release];
}

- (void)CurrentChange:(int)Index:(double)current
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	if(globalIndex == Index) {
		[currentField setDoubleValue:current];
		[currentTrackBar setDoubleValue:current];
	}
	[pool release];
}

- (void)InputChange:(int)Index:(int)State
{
	[[inputs cellWithTag:Index] setState:State];
}

/*
* 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];
	
	CPhidgetStepper_create(&stepper);
	
	CPhidget_set_OnAttach_Handler((CPhidgetHandle)stepper, gotAttach, self);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)stepper, gotDetach, self);
	CPhidgetStepper_set_OnPositionChange_Handler(stepper, gotPositionChange, self);
	CPhidgetStepper_set_OnVelocityChange_Handler(stepper, gotSpeedChange, self);
	CPhidgetStepper_set_OnCurrentChange_Handler(stepper, gotCurrentChange, self);
	CPhidgetStepper_set_OnInputChange_Handler(stepper, gotInputChange, self);
	
	if(remote)
		CPhidget_openRemote((CPhidgetHandle)stepper, serial, NULL, NULL);
	else
		CPhidget_open((CPhidgetHandle)stepper, serial);
}

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