/*
 * 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"


@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];
		
		wordlist = [NSMutableArray array];
	}
	return self;
}

/**
 * Action that filters through all the words with the given tiles and then produces
 * the list
 */
- (IBAction)findWords:(id)sender
{
	wordlist = [NSMutableArray array];
	
	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)]];
	}
	
	NSCharacterSet *charset = [NSCharacterSet characterSetWithCharactersInString:tileString];
	NSCharacterSet *charsetInverted = [charset invertedSet];
	
	for (NSString *word in dictionary)
	{
		if ([word length] > tileCount)
		{
			continue;
		}
		
		if ([word rangeOfCharacterFromSet:charsetInverted].location == NSNotFound)
		{
			[wordlist addObject:[[Word alloc] initWithWord:word]];
		}
	}
}

@end
