/* 
 * ToDoList - list that sorts its elements based on the priority of the
 * 	ToDoItems that it contains
 *
 * You may freely copy, distribute and reuse the code in this example.
 * This code is provided AS IS without warranty of any kind, expressed 
 * or implied, as to its fitness for any particular use.
 *
 * Copyright 1995 Ralph Zazula (rzazula@next.com).  All Rights Reserved.
 *
 */

#import "ToDoList.h"
#import "ToDoItem.h"
#import <time.h>
#import <stdlib.h>

@implementation ToDoList

static int toDoCompare(const void *x, const void *y)
{
	ToDoItem *xi = *(ToDoItem **)x;
	ToDoItem *yi = *(ToDoItem **)y;
	long xp = [xi priority];
	long yp = [yi priority];
	
	/* sort by priority */
	if(xp != yp) {
		return yp - xp;
	}
	
	/* items of similar priorty sort by creation date */
	return [yi startDate] - [xi startDate];
}

- sort
{
	qsort((ToDoItem **)dataPtr, numElements, sizeof(id), toDoCompare);
	return self;
}

- insertObject:anObject at:(unsigned)index
{
	if(![super insertObject:anObject at:index]) {
		return nil;
	}
	[self sort];
	return self;
}

@end

