/* Controller.m:
 * A quick demo of how to get around a problem with qualifiers that include
 * reference to attributes from a one-to-one relationship.
 *
 * You may freely copy, distribute, and reuse the code in this example.
 * NeXT disclaims any warranty of any kind, expressed or  implied, as to its
 * fitness for any particular use.
 *
 * Written by: Mai Nguyen, NeXT Developer Support
 *
 *
 */
#import "Controller.h"

#define INSTALL_MODEL NXLocalizedString("Please install OracleDemo.dbmodel into your ~/Library/Databases directory and restart.", NULL, "Notify user that OracleDemo.dbmodel must be installed in his local Databases directory.")

@implementation Controller
/*
* Extract the actual database and recordlist from the DBModule UI Object
*/ 
-appDidInit:sender
{	
	/*  Notify the user if the database can't be found */
	if (!(dbDatabase = [DBDatabase findDatabaseNamed:"OracleDemo" connect:YES])) {
		NXRunAlertPanel(NULL,INSTALL_MODEL, "OK", NULL, NULL);
		return self;
	}
	[dbDatabase setDelegate:self];			
	dbFetchGroup = [dbModule rootFetchGroup];
	rootEntity = [dbDatabase entityNamed:"Order"];
		/* Another workaround is to do this via a connection from the 
		 * relationship attribute to the File's Owner. Then, you don't
		 * need to add an expression explicitly, and the next 2 lines
		 * of code are no longer needed.
		 */
	dbExpression = [[DBExpression alloc] initForEntity: rootEntity
					fromDescription:"customer.customerID"];
	[dbFetchGroup addExpression:dbExpression];

	dbQualifier = [[DBQualifier alloc] initForEntity:rootEntity 
			fromDescription:"customer.state = %s", "CA"];
	
	[dbFetchGroup fetchContentsOf:rootEntity usingQualifier:dbQualifier];
	[dbQualifier free];
	[dbTableView display];
	return self;
}

- fetch:sender
{
	const char * newState;
	
	newState = (const char *)[inputField stringValue];
	if ( !(strcmp(newState, "")) )
		dbQualifier = nil;
	else
		dbQualifier = [[DBQualifier alloc] initForEntity:rootEntity
				fromDescription: "customer.state = %s", newState];
	[dbFetchGroup fetchContentsOf:rootEntity usingQualifier:dbQualifier];
	[dbQualifier free];
	[dbTableView display];
	return self;
}

- free
{
	if (dbQualifier)
		[dbQualifier free];
	if (dbExpression)
		[dbExpression free];
	return[super free];
}

/* DBDatabase delegate methods to log error messages and SQL queries */

- (BOOL)db:aDb willEvaluateString:(const char*)aString usingBinder:aBinder
{
	fprintf(stderr, "SQL query:%s\n", aString);
	return YES;
}



@end
