#import "PAStringList.h"

/******************************************************************************
PAStringList

	The PAStringList (a subclass of Storage) is a convenient way to deal with lists of character strings. It contains methods for adding strings, inserting strings, sorting strings and searching for strings.
		
	The PAStringList can also add strings from a delimited string (such as the ones passed to an app by the workspace). The delimiters can be supplied or assumed to be white space.
	
	Finally, the PAStringList implements a browser delegate method so that it can easily display itself if set to be a browser delegate.

	To use this object inside of InterfaceBuilder, simply drag its icon from the palettes window into the suitcases window. Then drag in a browser and set its delegate to be the stringlist. Type in some entries into PAStringList's inspector and test interface. The browser fills up!

	Copyright 1992, Jeff Martin (jmartin@next.com) (415) 780-3833.
******************************************************************************/
	
@implementation PAStringList : Storage

- init
{ 
	// Customize Storage to be 'char *' only
	[super initCount:0 elementSize:4 description:"*"];

	// StringList is assumed to be sorted by default and when emptied
	//    Adding a string without sorted flag causes 'isSorted' to be set to NO
	isSorted = YES;
	return self; 
}

/******************************************************************************
	addString:, addStringIfAbsent: addStringNoCopy: addStringIfAbsentNoCopy:
	addString:at:, addStringIfAbsent:at:, addStringIfAbsent:at:
	addStringSorted:, addStringIfAbsentSorted:, addStringIfAbsentNoCopySorted:

	These methods are convenience methods that simply call the master addString method and provide shorter names for cleaner use assuming the defaults of ifAbsent=NO, noCopy=NO, sorted=NO and at=count. Returns the result of the main addString method (self).
******************************************************************************/
- addString:(const char *)string { return 
	[self addString:string ifAbsent:NO noCopy:NO sorted:NO at:[self count]];  }
- addStringIfAbsent:(const char *)string { return 
	[self addString:string ifAbsent:YES noCopy:NO sorted:NO at:[self count]]; }
- addStringNoCopy:(const char *)string { return 
	[self addString:string ifAbsent:NO noCopy:YES sorted:NO at:[self count]]; }
- addStringIfAbsentNoCopy:(const char *)string { return
	[self addString:string ifAbsent:YES noCopy:YES sorted:NO at:[self count]];}

- addString:(const char *)string at:(int)at;
{ return [self addString:string ifAbsent:NO noCopy:NO sorted:NO at:at]; }
- addStringIfAbsent:(const char *)string at:(int)at;
{ return [self addString:string ifAbsent:YES noCopy:NO sorted:NO at:at]; }
- addStringNoCopy:(const char *)string at:(int)at;
{ return [self addString:string ifAbsent:NO noCopy:YES sorted:NO at:at]; }
- addStringIfAbsentNoCopy:(const char *)string at:(int)at;
{ return [self addString:string ifAbsent:YES noCopy:YES sorted:NO at:at]; }

- addStringSorted:(const char *)string;
{ return [self addString:string ifAbsent:NO noCopy:NO sorted:YES at:0]; }
- addStringIfAbsentSorted:(const char *)string;
{ return [self addString:string ifAbsent:YES noCopy:NO sorted:YES at:0]; }
- addStringNoCopySorted:(const char *)string;
{ return [self addString:string ifAbsent:NO noCopy:YES sorted:YES at:0]; }
- addStringIfAbsentNoCopySorted:(const char *)string;
{ return [self addString:string ifAbsent:YES noCopy:YES sorted:YES at:0]; }

/******************************************************************************
	addString:ifAbsent:noCopy:sorted:at:

	This method provides a flexible method for adding strings to the list. The ifAbsent flag specifies whether a string should be added if it already exists. The noCopy flag specifies whether the given string should be used (or copied). The sorted flag specifies whether the string should be added alphabetically. The at value specifies where the string should be inserted at if it is not added alphabetically. Returns self.
******************************************************************************/
- addString:(const char *)string ifAbsent:(BOOL)ifAbsent noCopy:(BOOL)noCopy sorted:(BOOL)sorted at:(int)at
{
	BOOL stringExists;
	int index = (ifAbsent || sorted)? 
		[self indexOfString:string exists:&stringExists] : 0;

	// If we add only if absent and string is in list return self
	if(ifAbsent && stringExists) return self;

	// If not noCopy (in other words, if copy) make copy
	if(!noCopy) string = NXCopyStringBufferFromZone(string, [self zone]);

	// If sorted, get index else add at 'at'; otherwise set isSorted flag to NO
	if(sorted) at = index; else isSorted = NO;
	
	// Add the string and return
	[self insertElement:(char **)&string at:at];
	return self;
}

/******************************************************************************
	addStrings, addPAStringList

	These methods allow for lists of strings to be added either from a char ** or from a PAStringList object. Returns self.
******************************************************************************/
- addStrings:(const char *const*)strings { return 
	[self addStrings:strings ifAbsent:NO noCopy:NO sorted:NO at:[self count]];}
- addStrings:(const char *const*)strings ifAbsent:(BOOL)ifAbsent noCopy:(BOOL)noCopy sorted:(BOOL)sorted at:(int)at
{
	char **temp = (char **)strings;
	
	// Add each string individually, incrementing 'at' to preserve their order
	while(*temp) {
		[self addString:*temp ifAbsent:ifAbsent noCopy:noCopy 
			sorted:sorted at:at];
		at++; temp++;
	}
	
	// If 'noCopy' then we own the memory 'strings' and should free it
	if(noCopy) free((char *)strings);
	
	return self;
}

- addPAStringList:stringListObject 
{ return [self addStrings:[stringListObject strings]]; }
- addPAStringList:stringListObject ifAbsent:(BOOL)ifAbsent noCopy:(BOOL)noCopy sorted:(BOOL)sorted at:(int)at
{ return [self addStrings:[stringListObject strings] ifAbsent:ifAbsent 
		noCopy:noCopy sorted:sorted at:at]; }

/******************************************************************************
	addDelimitedStrings:delimiters:
	addDelimitedStrings:delimiters:ifAbsent:sorted:at:

	This method takes a delimited string (like the ones passed from the workspace) and searches for the given delimiters (NULL for general whitespace). It adds each string that it finds between the delimiters using the addString method. Returns self.
******************************************************************************/
- addDelimitedStrings:(const char *)string delimiters:(const char *)dels
{ return [self addDelimitedStrings:string delimiters:dels ifAbsent:NO  sorted:NO at:[self count]]; }
- addDelimitedStrings:(const char *)string delimiters:(const char *)dels ifAbsent:(BOOL)ifAbsent sorted:(BOOL)sorted at:(int)at
{
	static char defaultDels[] = {' ', '\t', '\n', '\r', '\0'};
	int delCount, i;
	char *currChar, *currString, *stringEnd;

	// Check to see if we were handed a bogus string
	if(!string || !strlen(string)) return self;

	// Check for default delimiter and get number of delimiters
	if(!dels) dels = defaultDels;
	delCount = strlen(dels) + 1;
	
	// Make copy of the string (going to use string as scratch)
	string = NXCopyStringBuffer(string);
	currChar = currString = (char *)string; 
	stringEnd = (char *)((int)string+strlen(string));
	
	// Look at each character until we pass null terminator(stringEnd)
	while(currChar <= stringEnd) {
		
		// Check the character against the delimiters
		for(i=0; i<delCount; i++)

			// If current character matches a delimiter add current string
			if(*currChar==dels[i]) {
			
				// Set delimiter to NULL('\0')
				*currChar = '\0'; 
				
				// Only add if there is something to add. Increment at.
				if(strlen(currString))
					[self addString:currString ifAbsent:ifAbsent noCopy:NO 
						sorted:sorted at:at++];

				// set currString to start of next string(just past curr del)
				currString = currChar + 1;
				break;
			}
		currChar++;
	}
	
	free((char *)string);
	return self;
}


/******************************************************************************
	(const char *const*)strings
	(const char *)stringAt:(int)at

	The strings methods returns all of the strings as an array of char pointers. This array is NOT null terminated.
	The stringAt: method returns the string at a particular index.
******************************************************************************/
- (const char *const*)strings	 { return (const char *const*)dataPtr; }
- (const char *)stringAt:(int)at { return *(char **)[self elementAt:at]; }


/******************************************************************************
	(BOOL)stringExists
	(unsigned int)indexOfString
	(unsigned int)indexOfString exists:(BOOL *)exists

	stringExists returns whether or not the string is already in the list. indexOfString returns either the strings current index or the index that it should be alphabetically(returning [self count] if not sorted).
	indexOfString:stringExists: is a composite method that returns both values in about the same amount of time that it takes to compute one.
******************************************************************************/
- (BOOL)stringExists:(const char *)string
{ BOOL exists; [self indexOfString:string exists:&exists]; return exists; }

- (unsigned)indexOfString:(const char *)string
{ return [self indexOfString:string exists:NULL]; }

- (unsigned)indexOfString:(const char *)string exists:(BOOL *)exists
{
	int index;
	
	// Assume the string won't be found
	if(exists) *exists = NO;

	// If list is empty or no string or zero strlen, return end of list
	if(![self count] || !string || !strlen(string)) return [self count];
	
	// If not sorted do sequential search
	if(!isSorted) {
		int i=0;
		for(i=0; i<[self count]; i++) 
			if([self stringAt:i] && (!strcasecmp(string, [self stringAt:i]))) 
				{ if(exists) *exists = YES; break; }

		index = i;
	}
	
	// Otherwise if it is sorted do a binary search
	else {
		int l = 0;						// lower index
		int u = [self count] - 1;		// upper index
		int m = 0;						// middle index
		int guess = 0;					// compare val.
		
		while(l <= u) {
			m = (l+u)/2;
			guess = strcasecmp([self stringAt:m], string);
			
			// If guess is too high, adjust the upper value
			if(guess>0) u = m-1;
			
			// If guess is too low, adjust the lower value
			else if(guess<0) l = m+1;
			
			// If guess is equal to string, set 'exists' flag and break
			else { if(exists) *exists = YES; break; }
		}

		// If last guess was right or too high index is m; if too low then m+1;
		if(guess>=0) index = m; else index = m+1;
	}

	return index;
}


/******************************************************************************
	removeString:(const char *)string
	removeStrings:(const char *const*)strings
	removeStringAt:(int)at

	These methods allow for the removal of strings by value or index. Returns self.
******************************************************************************/
- removeString:(const char *)string
{
	BOOL exists;
	int index = [self indexOfString:string exists:&exists];
	if(exists) [self removeStringAt:index];
	return self;
}
- removeStrings:(const char *const*)strings
{
	int i;
	for(i=0; i<[self count]; i++) [self removeString:strings[i]];
	return self;
}
- (char *)removeStringAt:(int)at
{
	char *string = (char *)[self stringAt:at];
	[self removeElementAt:at];
	if(![self count]) isSorted = YES;
	return string;
}

/******************************************************************************
	(BOOL)isSorted
	sortStrings:sender
	
	isSorted returns whether or not the list is currently considered to be sorted. Lists are set to be sorted by default and when empty. isSorted is set to NO when a string is added without the 'sorted' flag.
	sortStrings: sorts the stringList (ignoring case) and sets the sorted flag. Returns self.
******************************************************************************/
- (BOOL)isSorted	{ return isSorted; }

// Wrap around strcasecmp to accept 'char **' and NULL strings(NULLs to back)
static int strPtrCaseCmp(const void *s1, const void *s2)
{
	if(*(char **)s1==*(char **)s2) return 0;
	else if(!*(char **)s1) return 1; else if(!*(char **)s2) return -1;
	else return strcasecmp(*((char **)s1),*((char **)s2));
}

- sortStrings:sender
{
	qsort(dataPtr, [self count], sizeof(char *), strPtrCaseCmp); 
	isSorted = YES;
	return self;
}

/******************************************************************************
	Write and read the PAStringList for archiving.
******************************************************************************/
- write:(NXTypedStream *)stream
{	
	[super write:stream];
	NXWriteType(stream, "c", &isSorted);
	return self;
}

- read:(NXTypedStream *)stream
{
	[super read:stream];
	NXReadType(stream, "c", &isSorted);
	return self;
}

/******************************************************************************
	empty, freeStrings, free
	
	These methods empty the list, free the strings and free the list, respectively.
******************************************************************************/
- empty { isSorted = YES; return [super empty]; }

- freeStrings
{
	while([self count]) free([self removeStringAt:0]); 
	return self;
}

- free
{ 
	return [super free];
}

/******************************************************************************
	(int)browser:sender fillMatrix:matrix inColumn:(int)column
	
	This method is provided as a delegate method for browser to quickly display string list.
******************************************************************************/
- (int)browser:sender fillMatrix:matrix inColumn:(int)column
{
	int   i;
	id   cellList, theCell;
  
	// Set matrix to have the right number of cells.
	[matrix renewRows:[self count] cols:1];

	// Get list of cells from the matrix.
	cellList = [matrix cellList];

	// For each cell set its value, set whether it is a leaf or not and 
	//   mark it loaded.
	for(i=0;i<[cellList count];i++) {
		theCell = [cellList objectAt:i];
		[theCell setStringValue:[self stringAt:i]];
		[theCell setLeaf:YES];
		[theCell setLoaded:YES];
	}

	// Return the number of rows.
	return [self count];
}

// Interface Builder support
- (const char *)getInspectorClassName { return "PAStringListInspector"; }

@end

// Fixed indexOf: bug. Thanks Stefanie Herzer!