//
//  CrapsModel.m
//  Craps
//
//  Created by Rich on 1/19/11.
//  Copyright 2011 Swarthmore College. All rights reserved.
//

#import "CrapsModel.h"
#import <stdlib.h>

@interface CrapsModel()
@property int point;
@end

@implementation CrapsModel

@synthesize point, balance, ante;
@synthesize won, lost;
@synthesize highScore;

- (NSString *)filePath
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *docdir = [paths objectAtIndex:0];
	NSString *filename = [docdir stringByAppendingPathComponent:@"data.plist"];
	NSURL *file = [NSURL fileURLWithPath:filename];
	return file.path;
}

- (void)saveData
{
	NSDictionary *d = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:self.highScore] 
												  forKey:@"highscore"];

	BOOL result = [d writeToFile:[self filePath] atomically:YES];
	if (!result) {
		NSLog(@"Error saving high score");
	}
}


- (void)loadData
{
	NSDictionary *d = [NSDictionary dictionaryWithContentsOfFile:[self filePath]];
	if (d) {
		highScore = [[d objectForKey:@"highscore"] intValue];
	} else {
		highScore = 0;
	}
}

- (void)reset
{
	balance = 200;
	ante = 5;
}

- (id)init
{
	if (self = [super init]) {
		[self reset];
		[self loadData];
		if (balance > highScore) { highScore = balance; } 
	}
	return self;
}

- (int)rollDie {
	return arc4random() % 6 + 1;
}

- (BOOL)bankrupt {
	return self.balance == 0;
}

- (NSArray *)dice
{
	return [NSArray arrayWithObjects:[NSNumber numberWithInt:die1], [NSNumber numberWithInt:die2], nil];
}

- (void)playTurn {
	die1 = [self rollDie];
	die2 = [self rollDie];
	
	won = lost = NO;
	
	int total = die1 + die2;
	
	if (self.point == 0) {  //first roll
		if ((total == 2) || (total == 3) || (total == 12)) {
			lost = YES;
		} else if ((total == 7) || (total == 11)) {
			won = YES;
		} else {
			point = total;
		}
	} else {  //subsequent rolls
		if (total == 7) {
			lost = YES;
			self.point = 0;
		} else if (total == self.point) {
			won = YES;
			self.point = 0;
		} else {
			//nothing happens
		}
	}
	
	if (won) {
		balance += ante;
		if (balance > highScore) highScore = balance;
	} else if (lost) {
		balance -= ante;
		if (balance < ante) ante = balance;
	}
}


- (void)setAnte:(int)anAnte {
	if (self.point == 0) {
		ante = anAnte / 5 * 5;
		if (balance < ante) ante = balance;
	}
}




@end
