//
//  HangmanModel.m
//  Hangman
//
//  Created by Rich on 1/26/11.
//  Copyright 2011 Swarthmore College. All rights reserved.
//

#import "HangmanModel.h"

@interface HangmanModel()
@property (copy) NSString* mysteryWord;
@property (copy) NSString* revealedWord;
@end



@implementation HangmanModel

@synthesize badGuesses, maxGuesses;
@synthesize revealedWord, mysteryWord;
@synthesize won, lost;



- (NSString *)makeBlank:(NSString *)nonBlank
{
	NSMutableString* blankString = [[NSMutableString alloc] init];
	for (int i=0; i < [nonBlank length]; i++) {
		[blankString appendString:@"-"];
	}
	return [NSString stringWithString:blankString];
}
								


- (NSString *)chooseWord
{
	NSString *filePath = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"txt"];  
	NSArray *wordlist = nil;
	if (filePath) {
		wordlist = [NSArray arrayWithContentsOfFile:filePath];
	} 
	if (!wordlist) {
		wordlist = [NSArray arrayWithObjects:@"swarthmore", @"iphone", @"objective", @"snow", nil];
	}
	int randposn = arc4random() % [wordlist count];
	return [wordlist objectAtIndex:randposn];	
}



- (id)init 
{
	if (self = [super init]) 
	{
		self.mysteryWord = [self chooseWord];		
		self.revealedWord = [self makeBlank:self.mysteryWord];
		
		badGuesses = 0;
		maxGuesses = 9;
	}
	return self;	
}



							  
- (NSString *)newGame
{
	self.mysteryWord = [self chooseWord];
	self.revealedWord = [self makeBlank:self.mysteryWord];
	self.badGuesses = 0;
	self.won = NO;
	self.lost = NO;
	
	return revealedWord;
}

- (NSString *)guessLetter:(NSString *)letter
{
	BOOL foundLetter = NO;
	for (int i = 0; i < [mysteryWord length]; i++) {
		NSRange range = NSMakeRange(i, 1);
		if ([mysteryWord compare:letter options:NSCaseInsensitiveSearch range:range] == NSOrderedSame) {
			self.revealedWord = [revealedWord stringByReplacingCharactersInRange:range withString:letter];
			foundLetter = YES;
		}
	}
	
	if (!foundLetter) badGuesses++;
	if ([mysteryWord compare:revealedWord options:NSCaseInsensitiveSearch] == NSOrderedSame) self.won = YES;
	if (badGuesses == maxGuesses) self.lost=YES;
	
	return revealedWord;
}


- (NSString *)giveUp
{
	lost = YES;
	self.revealedWord = mysteryWord;
	return revealedWord;
}


- (void)dealloc 
{
	[revealedWord release];
	[mysteryWord release];
	[super dealloc];
}

@end
