/* FFAdaptorTest.m:
 * 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 <appkit/appkit.h>
#import <dbkit/dbkit.h>
#import <objc/List.h>
#import <objc/NXBundle.h>
#import <sys/param.h>
#import <libc.h>

#import "FFAdaptorTest.h"

@implementation FFAdaptorTest

- appDidInit:sender
{
	NXRect viewFrame;
	
		/* Try to connect to the database specified using the FileFinderAdaptor
		 */
   	dbDatabase = [[DBDatabase alloc]init];	   
	[dbDatabase
		 connectUsingAdaptor:"FileFinderAdaptor"
		 andString:"/NextLibrary/Documentation/NextDev/ReleaseNotes"];
							
							
	if ( ![dbDatabase isConnected] ) {
			NXRunAlertPanel("Failure", "Cannot connect", "OK", NULL, NULL);
			return self;
	}
		/* Install the tableview into the custom view */
	[[dbTableView getFrame:&viewFrame] free];
	dbTableView = [[DBTableView alloc] initFrame:&viewFrame];
	[[window contentView] addSubview:dbTableView];

	[dbTableView setHorizScrollerRequired:YES];
	[dbTableView setVertScrollerRequired:YES];
	rootEntity = [dbDatabase entityNamed:"Files"];
  	dbModule = [[DBModule alloc] initDatabase:dbDatabase 
							entity:rootEntity];					
	dbFetchGroup = [dbModule rootFetchGroup];
	dbRecordList = [dbFetchGroup recordList];
	
	propList = [[List alloc] init];
	[rootEntity getProperties: propList];
	
	[dbRecordList setProperties:propList ofSource:rootEntity];
	[window disableFlushWindow];
	[self initTableView];
	[[window reenableFlushWindow] flushWindow];
	
	return self;

}

- initTableView
{
    int                 i,c;
    id                  prop;
	
    
    [numRecords setIntValue:[self rowCount]];
    c = [propList count];
    for (i = 0; i < c; i++) {
	prop = [propList objectAt:i];
	[dbTableView addColumn:prop 
		withFormatter:[[DBTextFormatter alloc] init]
		andTitle:(const char *)[prop name] at:(unsigned int)i];
    }
    [dbTableView setDataSource:self];
    [dbTableView display];

    [window makeKeyAndOrderFront:self];
    return self;
}

- showAll:sender
{
	[dbRecordList fetchUsingQualifier:nil];
	[dbTableView display];
	return self;
}


-window
{
	return window;
}

- windowWillClose:sender
{
	[dbRecordList free];
	return self;
}

- (unsigned)rowCount
{
	return ([[dbRecordList setLast] currentPosition]+1); /* zero based */
}

- (unsigned)columnCount
{
	return ([propList count]); /* zero based */
}

- getValueFor: aProperty at:(unsigned)index into:aValue
{
    [dbRecordList getValueFor:(id <DBProperties >)aProperty at:(unsigned)index
     into:(DBValue *) aValue];
    return self;
}

- setValueFor: aProperty at:(unsigned)index into:aValue
{
    [dbRecordList setValueFor:(id <DBProperties >)aProperty at:(unsigned)index
     into:(DBValue *) aValue];
    return self;
}


@end
