
#import "PGController.h"
#import "PowerGlove.h"

/* Internal functions */
void timedEntryHandler(DPSTimedEntry teNumber, double now, char *userData)
{
    id object = (id)userData;
    [object getPowerGloveData];
}

@implementation PGController

/* Action methods */
- showInfoPanel:sender
{
    if (infoPanel == nil) {
        if (![NXApp loadNibSection:"infopanel.nib" owner:self withNames:NO]) {
	    return nil;
	}
    }
    [infoPanel makeKeyAndOrderFront:nil];
    return self;
}

- showPreferencesPanel:sender
{
    if (preferencesPanel == nil) {
        if (![NXApp loadNibSection:"preferencespanel.nib" owner:self withNames:NO]) {
	    return nil;
	}
	/* Initialize sample delay settings */
        [sampleDelaySlider setMinValue:(double)0.001];
        [sampleDelaySlider setMaxValue:(double)0.5];
        [sampleDelaySlider setFloatValue:sampleDelay];
        [sampleDelayField setFloatValue:sampleDelay];
    }
    [preferencesPanel makeKeyAndOrderFront:nil];
    return self;
}

- setSampleDelay:sender
{
    sampleDelay = [sender floatValue];
    [sampleDelayField setFloatValue:sampleDelay];
    
    /* Replace old timed entry with a new one */
    if (powerGloveTE) {
        DPSRemoveTimedEntry(powerGloveTE);
    }
    powerGloveTE = DPSAddTimedEntry(sampleDelay,
                                   (DPSTimedEntryProc)timedEntryHandler,
				   self, NX_BASETHRESHOLD);
    return self;
}

/* Misc. methods */
- getPowerGloveData
{
    /* Update buttons */
    [aButton setState:[powerGlove aPressed]];
    [bButton setState:[powerGlove bPressed]];
    [startButton setState:[powerGlove startPressed]];
    [selectButton setState:[powerGlove selectPressed]];
    [upButton setState:[powerGlove padUp]];
    [downButton setState:[powerGlove padDown]];
    [leftButton setState:[powerGlove padLeft]];
    [rightButton setState:[powerGlove padRight]];

    /* Update finger value form fields */
    [ringSlider setIntValue:[powerGlove ring]];
    [middleSlider setIntValue:[powerGlove middle]];
    [indexSlider setIntValue:[powerGlove index]];
    [thumbSlider setIntValue:[powerGlove thumb]];
        
    /* Update position and rotation form fields */
    [xField setIntValue:[powerGlove gloveX]];
    [yField setIntValue:[powerGlove gloveY]];
    [zField setIntValue:[powerGlove gloveZ]];
    [rollField setIntValue:(int)[powerGlove gloveRot]*30];

    [powerGloveView display];
    return self;
}


@end

/* Delegate methods */
@implementation PGController(ApplicationDelegate)

- appDidInit:sender
{
    /* Initialize the PowerGlove */
    [powerGlove init];
    [powerGlove setxHyst:0 yHyst:0 zHyst:0];
    
    /* Set up timed entry to get glove data periodically */
    sampleDelay = 0.1;
    powerGloveTE = DPSAddTimedEntry(sampleDelay,
                                   (DPSTimedEntryProc)timedEntryHandler,
				   self, NX_BASETHRESHOLD);
    return self;
}

@end
