#import "PhidgetFrequencyCounterController.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 gotCount(CPhidgetFrequencyCounterHandle phid, void *context, int ind, int time, int counts) {
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	[(id)context performSelectorOnMainThread:@selector(Count:)
								  withObject:[NSArray arrayWithObjects:[NSNumber numberWithInt:ind], [NSNumber numberWithInt:time], [NSNumber numberWithInt:counts], nil]
							   waitUntilDone:NO];
	[pool release];
	return 0;
}

@implementation PhidgetFrequencyCounterController

- (IBAction)setInputEnabled:(id)sender
{
	CPhidgetFrequencyCounter_setEnabled(freq, [sender selectedTag], [[sender cellWithTag:[sender selectedTag]] state]);
}

- (IBAction)setFilter:(id)sender
{
	CPhidgetFrequencyCounter_setFilter(freq, [sender selectedTag], [[sender cellWithTag:[sender selectedTag]] indexOfSelectedItem]+1);
}

- (IBAction)setTimeout:(id)sender
{
	CPhidgetFrequencyCounter_setTimeout(freq, [sender selectedTag], [[sender cellWithTag:[sender selectedTag]] intValue]*1000);
	[[timeoutFields cellWithTag:[sender selectedTag]] setIntValue:[sender intValue]];
}

- (void)phidgetAdded:(id)nothing
{
	int serial, version, i;
	const char *name;
	CPhidget_DeviceID devid;

	CPhidget_getSerialNumber((CPhidgetHandle)freq, &serial);
	CPhidget_getDeviceVersion((CPhidgetHandle)freq, &version);
	CPhidget_getDeviceName((CPhidgetHandle)freq, &name);
	CPhidget_getDeviceID((CPhidgetHandle)freq, &devid);
	CPhidgetFrequencyCounter_getFrequencyInputCount(freq, &numInputs);
	
	[connectedField setStringValue:[NSString stringWithCString:name]];
	[serialField setIntValue:serial];
	[versionField setIntValue:version];
	[numInputsField setIntValue:numInputs];
	
	for(i=0;i<numInputs;i++)
	{
		CPhidgetFrequencyCounter_FilterType filter;
		int timeout;
		double frequency;
		int enabled;
		
		if(!CPhidgetFrequencyCounter_getEnabled(freq, i, &enabled))
		{
			[[enabledChecks cellWithTag:i] setState:enabled];
		}
		
		if(!CPhidgetFrequencyCounter_getFilter(freq, i, &filter))
		{
			[[filterComboBoxes cellWithTag:i] selectItemAtIndex:filter-1];
		}
		
		if(!CPhidgetFrequencyCounter_getTimeout(freq, i, &timeout))
		{
			[[timeoutSliders cellWithTag:i] setMinValue:100];
			[[timeoutSliders cellWithTag:i] setMaxValue:100000];
			[[timeoutSliders cellWithTag:i] setIntValue:(timeout/1000)];
			[[timeoutFields cellWithTag:i] setIntValue:(timeout/1000)];
		}
		
		if(!CPhidgetFrequencyCounter_getFrequency(freq, i, &frequency))
		{
			[[freqFields cellWithTag:i] setStringValue:[NSString stringWithFormat:@"%0.2lf",frequency]];
		}
	}
	
	[inputsBox setHidden:FALSE];	
	
	NSRect frame = [mainWindow frame];
	int 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];
	[mainWindow display];
}

- (void)phidgetRemoved:(id)nothing
{
	[connectedField setStringValue:@"Nothing"];
	[serialField setStringValue:@""];
	[versionField setStringValue:@""];
	[numInputsField setStringValue:@""];
	
	[inputsBox setHidden:TRUE];
	
	NSRect frame = [mainWindow frame];
	int heightChange = frame.size.height - 191;
	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)Count:(NSArray *)countData
{
	double frequency;
	if(!CPhidgetFrequencyCounter_getFrequency(freq, [[countData objectAtIndex:0] intValue], &frequency))
	{
		[[freqFields cellWithTag:[[countData objectAtIndex:0] intValue]] 
		 setStringValue:[NSString stringWithFormat:@"%0.2lf",frequency]];
	}
}

/*
* 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];
	
	CPhidgetFrequencyCounter_create(&freq);
	
	CPhidget_set_OnAttach_Handler((CPhidgetHandle)freq, gotAttach, self);
	CPhidget_set_OnDetach_Handler((CPhidgetHandle)freq, gotDetach, self);
	CPhidgetFrequencyCounter_set_OnCount_Handler(freq, gotCount, self);
	
	if(remote)
		CPhidget_openRemote((CPhidgetHandle)freq, serial, NULL, NULL);
	else
		CPhidget_open((CPhidgetHandle)freq, serial);
}

- (void)windowWillClose:(NSNotification *)aNotification {
	//Because this event is called twice
	if(freq)
	{
		CPhidget_close((CPhidgetHandle)freq);
		CPhidget_delete((CPhidgetHandle)freq);
		freq = NULL;
	}
	[NSApp terminate:self];
}

- (void)setPicture:(int)version:(CPhidget_DeviceID)devid
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSString *imgPath;
	
	switch(devid)
	{
		case PHIDID_FREQUENCYCOUNTER_2INPUT:
			imgPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"1054_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