#import "PhidggetTemperatureSensorController.h"

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 gotTemperatureChange(CPhidgetTemperatureSensorHandle phid, void *context, int ind, double val) {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[(id)context performSelectorOnMainThread:@selector(TemperatureChange:)
								  withObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:ind], [NSNumber numberWithDouble:val], nil]
							   waitUntilDone:NO];
	[pool release];
	return 0;
}

@implementation PhidggetTemperatureSensorController

- (IBAction)choseThermocoupleType:(id)sender
{
	double tempMax, tempMin;
	
	if([[[sender selectedCell] titleOfSelectedItem] isEqualToString:@"K"])
		CPhidgetTemperatureSensor_setThermocoupleType(temp, [sender selectedColumn], PHIDGET_TEMPERATURE_SENSOR_K_TYPE);
	else if([[[sender selectedCell] titleOfSelectedItem] isEqualToString:@"J"])
		CPhidgetTemperatureSensor_setThermocoupleType(temp, [sender selectedColumn], PHIDGET_TEMPERATURE_SENSOR_J_TYPE);
	else if([[[sender selectedCell] titleOfSelectedItem] isEqualToString:@"E"])
		CPhidgetTemperatureSensor_setThermocoupleType(temp, [sender selectedColumn], PHIDGET_TEMPERATURE_SENSOR_E_TYPE);
	else if([[[sender selectedCell] titleOfSelectedItem] isEqualToString:@"T"])
		CPhidgetTemperatureSensor_setThermocoupleType(temp, [sender selectedColumn], PHIDGET_TEMPERATURE_SENSOR_T_TYPE);
	
	CPhidgetTemperatureSensor_getTemperatureMax(temp, [sender selectedColumn], &tempMax);
	CPhidgetTemperatureSensor_getTemperatureMin(temp, [sender selectedColumn], &tempMin);
	
	[temperatureRangeField setStringValue:[NSString stringWithFormat:@"%0.0f°C - %0.0f°C",tempMin,tempMax]];
}

- (IBAction)setChangeTrigger:(id)sender
{
	int i;
	for(i=0;i<numInputs;i++)
		CPhidgetTemperatureSensor_setTemperatureChangeTrigger(temp, i, [triggerField floatValue]);
}

- (void)phidgetAdded:(id)nothing
{
	int serial, version;
	const char *name;
	CPhidget_DeviceID devid;
	double tempMax, tempMin, potMax, potMin, trigger;

	CPhidget_getSerialNumber((CPhidgetHandle)temp, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)temp, &version);
	CPhidget_getDeviceName((CPhidgetHandle)temp, &name);
	CPhidget_getDeviceID((CPhidgetHandle)temp, &devid);
	CPhidgetTemperatureSensor_getTemperatureInputCount(temp,&numInputs);
	CPhidgetTemperatureSensor_getTemperatureChangeTrigger(temp, 0, &trigger);
	CPhidgetTemperatureSensor_getTemperatureMax(temp, 0, &tempMax);
	CPhidgetTemperatureSensor_getTemperatureMin(temp, 0, &tempMin);
	CPhidgetTemperatureSensor_getPotentialMax(temp, 0, &potMax);
	CPhidgetTemperatureSensor_getPotentialMin(temp, 0, &potMin);
	
	[connectedField setStringValue:[NSString stringWithCString:name]];
	[serialField setIntValue:serial];
	[versionField setIntValue:version];
	[numInputsField setIntValue:numInputs];
	[triggerField setStringValue:[NSString stringWithFormat:@"%0.3f",trigger]];
	[temperatureRangeField setStringValue:[NSString stringWithFormat:@"%0.0f°C - %0.0f°C",tempMin,tempMax]];
	[potentialRangeField setStringValue:[NSString stringWithFormat:@"%0.2fmV - %0.2fmV",potMin,potMax]];
	
	[temperatureLabels renewRows:1 columns:numInputs];
	[temperatures renewRows:1 columns:numInputs];
	[potentials renewRows:1 columns:numInputs];
	[thermocoupleSelects renewRows:1 columns:numInputs];
	
	[sensorBox setHidden:FALSE];
	[settingsBox setHidden:FALSE];
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 422;
	frame.origin.y += heightChange;
	frame.size.height -= heightChange;
	[mainWindow setMinSize:frame.size];
	[mainWindow setFrame:frame display:YES animate:NO];
	
	[self setPicture:version:devid];
	[mainWindow display];
}

- (void)phidgetRemoved:(id)nothing
{
	[connectedField setStringValue:@"Nothing"];
	[serialField setStringValue:@""];
	[versionField setStringValue:@""];
	[numInputsField setStringValue:@""];
	[triggerField setStringValue:@""];
	[temperatureRangeField setStringValue:@""];
	[potentialRangeField setStringValue:@""];
	
	[sensorBox setHidden:TRUE];
	[settingsBox setHidden:TRUE];
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 205;
	frame.origin.y += heightChange;
	frame.size.height -= heightChange;
	[mainWindow setMinSize:frame.size];
	[mainWindow setFrame:frame display:YES animate:NO];
	
	[self setPicture:0:0];
	
	[mainWindow display];
}

- (void)TemperatureChange:(NSArray *)tempChangeData
{
	double ambient, pot;
	
	[[temperatures cellAtRow:0 column:[[tempChangeData objectAtIndex:0] intValue]] 
	 setStringValue:[NSString stringWithFormat:@"%0.4f",[[tempChangeData objectAtIndex:1] doubleValue]]];
	
	CPhidgetTemperatureSensor_getAmbientTemperature(temp, &ambient);
	[ambientTempField setStringValue:[NSString stringWithFormat:@"%0.3f", ambient]];
	
	CPhidgetTemperatureSensor_getPotential(temp, [[tempChangeData objectAtIndex:0] intValue], &pot);
	[[potentials cellAtRow:0 column:[[tempChangeData objectAtIndex:0] intValue]] 
	 setStringValue:[NSString stringWithFormat:@"%0.4f",pot]];
}

/*
* 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];
	
	CPhidgetTemperatureSensor_create(&temp);
	
	CPhidgetTemperatureSensor_set_OnTemperatureChange_Handler(temp, gotTemperatureChange, self);
	CPhidget_set_OnAttach_Handler((CPhidgetHandle)temp, gotAttach, self);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)temp, gotDetach, self);
	
	if(remote)
		CPhidget_openRemote((CPhidgetHandle)temp, serial, NULL, NULL);
	else
		CPhidget_open((CPhidgetHandle)temp, serial);
}

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

- (void)setPicture:(int)version:(CPhidget_DeviceID)devid
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSString *imgPath;
	
	switch(devid)
	{
		case PHIDID_TEMPERATURESENSOR:
			if(version <400)
				imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1051_1" ofType:@"icns"];
			else
				imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1051_2" ofType:@"icns"];
			break;
		case PHIDID_TEMPERATURESENSOR_4:
			imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1048_0" ofType:@"icns"];
			break;
		case PHIDID_TEMPERATURESENSOR_IR:
			imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1045_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];
}
@end