#import "MiniSQLExpression.h"

#import <eoaccess/eoaccess.h>

#import <foundation/NSUtilities.h>
#import <foundation/NSCharacterSet.h>

@implementation MiniSQLExpression:EOSQLExpression

- whereClauseForQualifier:(EOQualifier *) qualifier
    joinExpresssion:joinExpression
 // Builds an SQL WHERE clause using the qualifier and joinExpression 
{
    NSRange rangeOpen;
    NSRange rangeClose;

    NSMutableString    *newExpression =
	[NSMutableString stringWithCapacity:80];

    NSMutableString    *newQualification =
	[[qualifier expressionValueForContext:self] mutableCopy];

    NSMutableString    *newJoinExpression =
	[[joinExpression expressionValueForContext:self] mutableCopy];

    if (qualifier && newQualification && [newQualification length]) {
	for (rangeOpen = [newQualification rangeOfString:@"("];
	     (rangeOpen.length) != (unsigned int)0;
	     rangeOpen = [newQualification rangeOfString:@"("]) {
	    [newQualification deleteCharactersInRange:rangeOpen];
	}
	for (rangeClose = [newQualification rangeOfString:@")"];
	     rangeClose.length;
	     rangeClose = [newQualification rangeOfString:@")"]) {
	    [newQualification deleteCharactersInRange:rangeClose];
	}
	[newExpression appendString:newQualification];
    }
    if (joinExpression && newJoinExpression && [newJoinExpression length]) {
	for (rangeOpen = [newJoinExpression rangeOfString:@"("];
	     rangeOpen.length;
	     rangeOpen = [newJoinExpression rangeOfString:@"("]) {
	    [newJoinExpression deleteCharactersInRange:rangeOpen];
	}
	for (rangeClose = [newJoinExpression rangeOfString:@")"];
	     rangeClose.length;
	     rangeClose = [newJoinExpression rangeOfString:@")"]) {
	    [newJoinExpression deleteCharactersInRange:rangeClose];
	}
	if ([newQualification length] > 0) {
	    [newExpression appendString:@" AND "];
	}
	[newExpression appendString:newJoinExpression];
    }
    if ([newExpression length] > 0) {
	return[NSString stringWithFormat:@"WHERE %@", newExpression];
    } else {
	return @"";
    }
}

@end

