/* RandomDataSource.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.
 *
 * 
 *
 */

#import <appkit/appkit.h>
#import <objc/List.h>

#import "RandomDataSource.h"
#import "StringList.h"

@implementation RandomDataSource

- init
{
	[super init];
	rowList = [[List alloc] init];
	return self;
}



- setRows:(unsigned int) rowCount
{
	rows = rowCount;
	return self;
}

- setColumns:(unsigned int) columnCount
{
	columns = columnCount;
	return self;
}

- (unsigned int) rowCount
{
	return rows;
}

- (unsigned int) columnCount
{
	return columns;
}


- (const char *) getRandomString
{
	static const char       *text = NULL;
	static unsigned int	totalSize;
	char			buffer[100], *buf = buffer;
	const char		*probe;

	if (text == NULL) {
		int dummy; /* Not used */
		NXStream *stream = NXMapFile ("/usr/dict/words", NX_READONLY);
		if (!stream) return ""; /* Shouldn't happen... */
		NXGetMemoryBuffer(stream, &text, &totalSize, &dummy);
		NXCloseMemory(stream, NX_SAVEBUFFER); /* Free the stream but not the contents */
		srandom(time(0)); /* Randomize the random number generator */
	}	

	probe = (char *) (text + random() % (totalSize - 10));
	while (*probe++ != '\n');
	while (*probe != '\n' && buf - 99 < buffer) *buf++ = *probe++;
	*buf = 0;

	return NXCopyStringBuffer(buffer);
}


- empty
{
	unsigned int maxRow = [rowList count];
	unsigned int maxColumn = maxRow > 0 ? [[rowList objectAt:0] count] : 0;
	unsigned int i, j;

	for (i=0;  i < maxRow;  i++)
		for (j=0;  j < maxColumn;  j++)
			free([[rowList objectAt:i] objectAt:j]);
	
	[rowList freeObjects];
	return self;
}


- loadData
{
	unsigned int i, j;
	
	[self empty];
	for (i=0;  i < rows;  i++) {
		[rowList insertObject:[[StringList alloc] initCount:columns] at:i];
		for (j=0;  j < columns;  j++) {
			if (j != 1)
				[[rowList objectAt:i] addString:[self getRandomString] at:j];
			else
				[[rowList objectAt:i] addString:"inches" at:j];

		}
	}
	
	return self;
}

/* This method is called to display the strings in the tableview */
- getValueFor:index at:(unsigned int) aPosition into:aValue
{
	[aValue setStringValue:(char *) [[rowList objectAt:aPosition] stringAt:(int) index]];
	return self;
}

/* This method is called whenever the string is edited in the tableview */
- setValueFor:index at:(unsigned int) aPosition from:aValue
{
	char	*string;
	
	string = (char *)[[rowList objectAt:aPosition] removeStringAt:(int) index];
	free(string);
	string = NXCopyStringBuffer([aValue stringValue]);
	[[rowList objectAt:aPosition]
		addString:(const char *) string at: (int) index];
		 
	return self;
}


@end
