/*
 * Scrabbalize
 * Copyright (c) 2007, Blue Static <http://www.bluestatic.org>
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU 
 * General Public License as published by the Free Software Foundation; either version 2 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if not, 
 * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */

#import "AppController.h"
#import "Word.h"
#import "NSStringAdditions.h"

@implementation AppController

/**
 * Initializes the application and loads the dictionary archive
 */
- (id)init
{
	if (self = [super init])
	{
		NSString *path = [NSString stringWithFormat:@"%@/dictionary.ka", [[NSBundle mainBundle] resourcePath]];
		dictionary = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
	}
	return self;
}

/**
 * Action that filters through all the words with the given tiles and then produces
 * the list
 */
- (IBAction)findWords:(id)sender
{
	// remove the wordlist
	for (Word *word in [wordlist arrangedObjects])
	{
		[wordlist removeObject:word];
	}
	
	NSString *tileString = [tilesField stringValue];
	int tileCount = [tileString length];
	
	NSMutableArray *tiles = [NSMutableArray arrayWithCapacity:tileCount - 1];
	for (int i = 0; i < tileCount; i++)
	{
		[tiles addObject:[tileString substringWithRange:NSMakeRange(i, 1)]];
	}
	
	// create character sets from the tiles
	NSCharacterSet *charset = [NSCharacterSet characterSetWithCharactersInString:tileString];
	NSCharacterSet *charsetInverted = [charset invertedSet];
	
	// iterate over the dictionary to build our word list
	for (NSString *word in dictionary)
	{
		// word is larger than the number of tiles we have, remove
		if ([word length] > tileCount)
		{
			continue;
		}
		
		// if the word contains characters we don't have, then remove it
		if ([word rangeOfCharacterFromSet:charsetInverted].location != NSNotFound)
		{
			continue;
		}
		
		BOOL success = YES;
		for (NSString *tile in tiles)
		{
			if ([word occurrenceOfChar:tile] > [tileString occurrenceOfChar:tile])
			{
				success = NO;
			}
		}
		
		if (success)
		{
			[wordlist addObject:[[Word alloc] initWithWord:word]];
		}
	}
	
	// resort
	[wordlistView setSortDescriptors:nil];
	[wordlistView setSortDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"length" ascending:NO]]];
}

@end
