//
//  RendererController.m
//  OffScreenHapticRenderer
//
//  Created by Luke Pullella.
//  Copyright 2006 Luke Pullella. All rights reserved.
//

#import "RendererController.h"

@implementation RendererController

- (id) init
{
	self = [super init];
	if (self != nil)
	{
		deviceOn = NO;
	}
	
	return self;
}

- (void) dealloc
{
	if(deviceOn)
	{
		[hView stop];
		[hView release];
		[hShape release];
	}

	[super dealloc];
}


- (void) awakeFromNib
{
	// Fill Shape Selector
	NSMutableArray *shapeList = [NSMutableArray array];
	int i = 0;
	for(; i < shape_table_size; i++)
	{
		[shapeList addObject:[NSString stringWithCString:shape_table[i][1]]];
	}
	[shapeSelector addItemsWithTitles:shapeList];
	
	// Select the first item
	[shapeSelector selectItemAtIndex:0];
	
	// Create the haptic shape
	hShape = [objc_getClass(shape_table[0][0]) alloc];
	
	// Set current shape title
	[currentShape setStringValue:[NSString stringWithCString:shape_table[0][1]]];
}

- (IBAction)startStopDevice:(id)sender
{
	if(!deviceOn)
	{
		hView = [[HapticView alloc] init];
		
		if(hView)
		{
			[hView startDrawingOn:glView with:hShape];
			[deviceStatus setStringValue:@"Connected"];
			[startStopButton setTitle:@"Stop Haptic Device"];
			deviceOn = YES;
			[controlDrawer open];
		}
		else
		{
			[deviceStatus setStringValue:@"Connection Failed"];
		}
	}
	else
	{
		[controlDrawer close];
		[hView stop];
		[hView release];
		[deviceStatus setStringValue:@"Not Connected"];
		[startStopButton setTitle:@"Initialise Haptic Device"];
		deviceOn = NO;
	}
}

- (IBAction)selectNewShape:(id)sender
{
	if(!deviceOn)
		return;

	// Get index of selection
	int index = [sender indexOfSelectedItem]-1;
	
	// Create new shape class based on the class name in the shape lookup table
	HapticShape *newShape = [objc_getClass(shape_table[index][0]) alloc];
	
	// Update the current shape title
	[currentShape setStringValue:[NSString stringWithCString:shape_table[index][1]]];
	
	// Set the haptic view to render the new shape
	[hView changeShapeTo:newShape];
	
	// Remove the old shape
	[hShape release];
	
	// Save the new shape
	hShape = newShape;
}

- (IBAction)modifyShape:(id)sender
{
	switch([sender tag])
	{
		case SCALE_SLIDER:
			[hShape scaleEntity:[sender floatValue]];
			break;
		case ROTATE_X_SLIDER:
			[hShape rotateEntityX:[sender floatValue]];
			break;
		case ROTATE_Y_SLIDER:
			[hShape rotateEntityY:[sender floatValue]];
			break;
		case ROTATE_Z_SLIDER:
			[hShape rotateEntityZ:[sender floatValue]];
			break;
	}
	
	[hView drawScene];
}

@end
