
#import "DwellingQueryController.h"
#import <pudobjectmodel/WaterHeater.h>
@implementation DwellingQueryController


- awakeFromNib
{
	[queryEOController fetch:self];
	return [super awakeFromNib];
}

- (int)runAlertPanel:sender
{
	return NXRunAlertPanel("Invalid Dwelling Type","Cannot Find Dwelling Type beginning with  %s","Edit","Show Listing",NULL,[(TextField *)sender stringValue]);
}

- fetchFromTextField:sender
{
	BOOL found = NO;
		
	if ([(TextField *)sender stringValue]  && strlen([(TextField *)sender stringValue]) >0) {
	
		id theString = [NSString stringWithCString:[(TextField *)sender stringValue]];
		NSEnumerator *theEnum = [[queryEOController allObjects] objectEnumerator];
		EOGenericRecord * theRecord = nil;
		NSRange aRange = {0,[theString length]};
		unsigned mask = NSCaseInsensitiveSearch;

		while (!found && (theRecord = [theEnum nextObject])) {
			NSString *cmpKey = [theRecord objectForKey:@"CATEGORY_NAME"];
			found = ([cmpKey compare:theString
				options:mask
				range:aRange] == NSOrderedSame);
		}
			
		if (found)
			[queryEOController selectObjectAtIndex:[[queryEOController allObjects] indexOfObject:theRecord]];
	}
		
	if (found) 
		[self setObject:sender];
	else {
		int answer = 2;
		if ([[appController preferences] useAlertPanels] && [self respondsToSelector:@selector(runAlertPanel:)]) 
			answer = [self runAlertPanel:sender];
		if (answer == 0)
			[[tableView window] makeKeyAndOrderFront:self];
		else {
			NXBeep();
			[sender setStringValue:""];
			[sender selectText:self];
		}
	}
	
	return self;
}

- (void)setObject:sender
{
	id	currentWaterHeater = [rootEOController currentObject],
		currentDwellingCategory = [queryEOController currentObject];
	
	if (currentWaterHeater && currentDwellingCategory) {
		[currentWaterHeater setDWELLING_CATEGORY:[currentDwellingCategory objectForKey:@"CATEGORY_NAME"]];
	
			// This will update the query fields
		[appController controllerDidChangeSelection:rootEOController];
		
		[[appController rootEditController] registerOperation:TD_Update onObject:currentWaterHeater];

			// This line is only to update the UI with the new default value.
			// It has nothing to do with registering the edit to be saved.

		[appController resetMenuCells];
		[[tableView window] performClose:self];
		[[nextText window] makeKeyAndOrderFront:self];
		[nextText selectText:self];
	}
	
}


@end

