//
//  CommonWindowController.m
//  SimpleSearchApp
//
//  Created by ub on 24.07.09.
//  Copyright 2009 Udo Borkowski. All rights reserved.
//

#import "CommonWindowController.h"


@implementation CommonWindowController

@synthesize searchString;
@synthesize query;

- (id)initWithWindow:(NSWindow *)window;
{
	if (![super initWithWindow: window]) {
		return nil;
	}
	
	self.query = [[NSMetadataQuery alloc] init];

	return self;
}

// queryString must not be nil
- (NSPredicate*)predicateForString:queryString;
{
	NSString* s = [NSString stringWithFormat:@"%@*", queryString];
	NSPredicate * predicate = [NSPredicate predicateWithFormat:
							   @"kMDItemTextContent like[cd] %@", s];
	return predicate;
}

- (BOOL)updatePredicate;
{
	if (self.searchString == nil) {
		return NO;
	}
	
    [self.query setPredicate: 
	 [self predicateForString: self.searchString]];
	
    return YES;
}

- (void)onSearchStringChanged;
{
	if ([self updatePredicate]) {
		[self.query startQuery];
	}
}

- (void)setSearchString:(NSString *)value;
{
    if (![self.searchString isEqualToString:value]) {
        searchString = [value copy];
		[self onSearchStringChanged];
    }
}

@end
