
#import "Dice.h"

void rollHandler(DPSTimedEntry teNumber, double now, void *userData)
{
    id obj = (id)userData;
    [obj animateRoll];
}
 
@implementation Dice

- awakeFromNib
{
	id myBundle = [NXBundle bundleForClass:[self class]];
	char path[MAXPATHLEN+1];

	if ([myBundle getPath:path forResource:"one" ofType:"tiff"])
		image[1] = [[NXImage  alloc] initFromFile:path];
	if ([myBundle getPath:path forResource:"two" ofType:"tiff"])
		image[2] = [[NXImage  alloc] initFromFile:path];
	if ([myBundle getPath:path forResource:"three" ofType:"tiff"])
		image[3] = [[NXImage  alloc] initFromFile:path];
	if ([myBundle getPath:path forResource:"four" ofType:"tiff"])
		image[4] = [[NXImage  alloc] initFromFile:path];
	if ([myBundle getPath:path forResource:"five" ofType:"tiff"])
		image[5] = [[NXImage  alloc] initFromFile:path];
	if ([myBundle getPath:path forResource:"six" ofType:"tiff"])
		image[6] = [[NXImage  alloc] initFromFile:path];

	[dieButton1 setImage:image[1]];
	[dieButton2 setImage:image[6]];
	
	isEnabled = YES;

	if ([myBundle getPath:path forResource:"roll" ofType:"snd"])
		rollSound = [[SoundEffect allocFromZone:[self zone]] initFromSection:path];	
    
	return self; 
}

- animateRoll 
{
    if(rollCount < NUMBER_TO_ROLL) {
	//die1 = (int) randBetween(1.0, 7.0);
	//die2 = (int) randBetween(1.0, 7.0);
	die1 = [dealer randomIntBetween:1 :6];
	die2 = [dealer randomIntBetween:1 :6];
	
	//[dieButton1 setIcon:imageName[die1]];
	//[dieButton2 setIcon:imageName[die2]];
	[dieButton1 setImage:image[die1]];
	[dieButton2 setImage:image[die2]];
	
	rotations = 0;
	nextRotation = nextRotation+1;
	rollCount++;

	NXPing();
	
    } else {
        DPSRemoveTimedEntry(animateTE);
	animateTE=0;
        
	[self enableRoll:self];
	
	[dealer playerDidThrow:self];
	
	rollCount = 0;
    }
     
    return self;
}

- disableRoll:sender
{
	[dieButton1 setEnabled:NO];
	[dieButton2 setEnabled:NO];
    
    return self;
}

- enableRoll:sender
{
    if(isEnabled)
	{
		[dieButton1 setEnabled:YES];
		[dieButton2 setEnabled:YES];
	}
    
    return self;
}

- getDiceValues:(int *)d1 :(int *)d2
{
    *d1 = die1;
    *d2 = die2;
    
    return self;
}

- roll:sender
{
    if([dealer playerWillThrow:self] == NO) return nil;
    
	[rollSound play:1.0 pan:0.0];
	
    [self disableRoll:self];
    
    rollCount = 0;
    rotations = 0;
    nextRotation = 1;
    
    animateTE = DPSAddTimedEntry(.05, (DPSTimedEntryProc)rollHandler, self, NX_BASETHRESHOLD);
    	
    return self;
}

- setEnabled:(BOOL)flag
{
	[dieButton1 setEnabled:flag];
	[dieButton2 setEnabled:flag];
	
	isEnabled = flag;
	
	return self;
}


@end
