
/* AssignmentTracker X http://www.atxproject.net - (c) 2003-2006, Colin Wheeler ( colin@atxproject.net )
 * ATXCoreController.m Created by Colin Wheeler on June 25, 2006
 * 
 * Contributor(s):
 *	Colin Wheeler
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
 * General Public License version 2 as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
 * Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if not,
 * write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#import "ATXCoreController.h"
#import "ATXPresentationManager.h"
#import "ATXLogUtilities.h"

/* DEBUG MODE FOR MORE VERBOSE LOGS */
#ifndef VERBOSE_MODE
#define VERBOSE_MODE
#endif

#define ATXCORECONTROLLER_FINISH_SETUP @"ATXCORECONTROLLER_FINISH_SETUP"
#define LAST_UNIQUE_SOURCELIST_ID @"LAST_UNIQUE_SOURCELIST_ID"
#define ATX_RETURN_FROM_STARTUPWIZARD_COMPLETE @"ATX_RETURN_FROM_STARTUPWIZARD_COMPLETE"

@implementation ATXCoreController

#pragma mark -
#pragma mark Init Methods

- (id)init 
{
    self = [super init];
    if (self != nil) {
        // initialization code
		nc = [NSNotificationCenter defaultCenter];
		defaults = [NSUserDefaults standardUserDefaults];
		
		/* Initially we should assume this is false until we check this more
			thouroughly later on */
		[defaults setBool:NO forKey:ATX_RETURN_FROM_STARTUPWIZARD_COMPLETE];
		
		currentAssignments = [[NSMutableArray alloc] init];
    }
	//NSLog(@"%s", _cmd);
	QuietLog(@"%s", _cmd);
	//
    return self;
}

- (void) dealloc
{
	nc = nil;
	defaults = nil;
	lastUniqueId = nil;
	[filterPredicateString release];
	[currentAssignments release];
	
	[super dealloc];
}

- (void)awakeFromNib
{
	[genericCategoriesController setEditable:NO];
	
	/* Checking to see if there is any data in the source list which 
	 * would indicate that this document has been setup
	 *
	 * yes this is more painful than a simple [sourceList count] check
	 * but no where near as painful as Sphere Break
	 */
	NSManagedObjectContext *moc = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSError *fetchError = nil;
    NSArray *fetchResults;
	
	@try {
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"group"
												  inManagedObjectContext:moc];
		
        [fetchRequest setEntity:entity];
        fetchResults = [moc executeFetchRequest:fetchRequest error:&fetchError];
    } @finally {
		//NSLog(@"[ATXCoreController] fetch request is now deallocd");
		QuietLog(@"[ATXCoreController] fetch request is now deallocd");
        [fetchRequest release];
    }
	
	if((fetchResults == nil) || ([fetchResults count] == 0) || (fetchError != nil))
	{
#ifdef VERBOSE_MODE
		//NSLog(@"[ATXCoreController] This is a document with no information!!!");
		QuietLog(@"[ATXCoreController] This is a document with no information!!!");
		//NSLog(@"[ATXCoreController] Beginning Startup Wizard...");
		QuietLog(@"[ATXCoreController] Beginning Startup Wizard...");
#endif
		
		[self presentStartupWizard];
		
		lastUniqueId = 10;
		
	} else {
#ifdef VERBOSE_MODE
		//NSLog(@"This Document has %i items in the source list",[fetchResults count]);
		QuietLog(@"This Document has %i items in the source list", [fetchResults count]);
#endif
		/* Send a notification which ATXPresentationManager responds to, to load the 
		   assignments view in the presentation box 
		*/
		[nc postNotificationName:@"SHOW_ASSIGNMENTS_VIEW" 
						  object:nil];
		
		/* Lets prepare our view now */
		
		lastUniqueId = [defaults integerForKey:LAST_UNIQUE_SOURCELIST_ID];
		
#ifdef VERBOSE_MODE
		//NSLog(@"[ATXCoreController] Retrieved Last unique id from preferences: %i",[defaults integerForKey:LAST_UNIQUE_SOURCELIST_ID]);
		QuietLog(@"[ATXCoreController] Retrieved Last unique id from preferences: %i",[defaults integerForKey:LAST_UNIQUE_SOURCELIST_ID]);
#endif
		
		/* Core Data uses NSMutableSet so we must sort sort sort... */
		[self sortObjectsInArrayControllers];
		
		/* Even if the user deletes the prefs we should make sure they can
			add and remove assignments */
		[defaults setBool:YES forKey:ATX_RETURN_FROM_STARTUPWIZARD_COMPLETE];
		
		/* We'll need to change this in the future to grab the font from preferences - Issue #16
		 * http://code.google.com/p/assignmenttrackerx/issues/detail?id=16&can=2&q=
		 */
		[assignmentNotesBox setFont:[NSFont fontWithName:@"Marker Felt" size:16.0]];
		
		[assignmentsTableController setSelectsInsertedObjects:YES];
	}
	/* end of startup data check */
	
	//***********************************//
	// Prepare other elements of the UI  //
	//***********************************//
	
	/*  Lets register for the appropriate notifications
		we'll need to use later on */
	[nc addObserver:self
		   selector:@selector(finishInitializingSetup)
			   name:ATXCORECONTROLLER_FINISH_SETUP
			 object:nil];
	
	[nc addObserver:self
		   selector:@selector(sourceListSelectionDidChange)
			   name:@"SOURCE_LIST_SELECTION_CHANGED"
			 object:nil];
	
	//Get the toolbar out of the way...
	[self setupToolbar];
	
	/*  Prevent the NSDatePickers from drawing their own background as
		we want them to use the gradient provided by RoundedBox otherwise
		they conflict heavily against the background for assignment detail view
		*/
	[assignedDatePicker setDrawsBackground:NO];
	[dueDatePicker setDrawsBackground:NO];
	
	/* This may need to be changed in the future, but for now this gives ATX 
		flexability as we could possibly switch over to a 2nd view for editing
		assignments
		*/
	[assignmentViewAndEditBox setContentView:assignmentViewingView];
}

- (void)sortObjectsInArrayControllers
{
	/* One sort descriptor to Rule them all! */
	NSSortDescriptor *ssort = [[NSSortDescriptor alloc] initWithKey:@"position" 
														  ascending:YES];
	
	/* Assignment Status Sort */
	[assignmentStatusController setSortDescriptors:[NSArray arrayWithObject:ssort]];
	
	/* Assignment Categories Sort */
	[genericCategoriesController setSortDescriptors:[NSArray arrayWithObject:ssort]];
	
	/* Assignment Priorities Sort */
	[assignmentsPrioritiesController setSortDescriptors:[NSArray arrayWithObject:ssort]];
	
	/* Let it go... */
	[ssort release];
}

- (void)setupToolbar
{
    NSToolbar *toolbar = [[NSToolbar alloc] initWithIdentifier:@"mainToolbar"];
    [toolbar autorelease];
    [toolbar setDelegate:self];
    [toolbar setAllowsUserCustomization:YES];
    [toolbar setAutosavesConfiguration:YES];
    [docWindow setToolbar:toolbar];
}

#pragma mark -
#pragma mark Accessor and Mutator Methods

/** NSManagedObjectContext pointer so we can do everything with Core Data */
- (NSManagedObjectContext *)managedObjectContext
{
	return [[[NSApplication sharedApplication] delegate] managedObjectContext];
}

/* The Current Assignments Array - This is the array the table view will be binded to
   so when the array changes the tableview will be updated */
- (NSMutableArray *)currentAssignments;
{
	return currentAssignments;
}

- (void)setTheCurrentAssignments:(NSArray *)newCurrentAssignments
{
	[currentAssignments release];
	currentAssignments = [newCurrentAssignments retain];
}

- (NSMutableString *)filterPredicateString
{
	return filterPredicateString;
}

- (void)setFilterPredicateString:(NSMutableString *)newFilterPredicateString
{
	[filterPredicateString release];
	filterPredicateString = [newFilterPredicateString copy];
}

#pragma mark -
#pragma mark View Methods

/** Checks to see if the NIB is loaded by testing if an assocociated NSView is nil.
    If said NSView is nil then a NSNib instance is allocd and instantiated with the 
    contents of the target nib.
    NOTE! This should be moved to a library soon so this function isn't unnecessarily
    replicated in every class that needs it.
*/
- (void)loadTheNib:(NSString *)nameOfNib withTestConnection:(NSView *)testView
{
	if (testView == nil) 
	{
#ifdef VERBOSE_MODE
		NSLog(@"Test View is nil");
#endif
		NSNib *nib = [[NSNib alloc] initWithNibNamed:nameOfNib bundle:[NSBundle bundleForClass:[self class]]];
		
		BOOL success = [nib instantiateNibWithOwner:self topLevelObjects:nil];
		[nib release];
		if (success != YES) 
		{
#ifdef VERBOSE_MODE
			[NSAlert alertWithMessageText:@"Error! Couldn't Load Nib!" 
						    defaultButton:@"Ok" 
						  alternateButton:nil 
							  otherButton:nil 
				informativeTextWithFormat:nil];
#endif
			NSLog(@"Error loading Nib: %@",nameOfNib);
			return;
		} else {
			NSLog(@"Nib loaded sucessfully");
		}
	}
}

/** Send a notification to the presentation manager to prepare and load the startup wizard nib file and view */
- (void)presentStartupWizard
{
	[nc postNotificationName:@"SHOW_STARTUP_WIZARD" object:nil];
}

/** Simply increments the lastUniqueId by 10 then saves the result to the defaults.
	This will need to be moved to be stored in the XML file later on. 
*/
- (void)incrementTheUniqueID
{
	lastUniqueId += 10;
	
	NSLog(@"[ATXCoreController] Incremented the UNIQUE_ID by 10 to -> %i",lastUniqueId);
	
	[defaults setInteger:lastUniqueId forKey:LAST_UNIQUE_SOURCELIST_ID];
}

- (void)sourceListSelectionDidChange
{
	//begin to determine what we need to display in the table
	// sourceItemType ( VIEW_ALL_ASSIGNMENTS_LIST || VIEW_COURSE_WITH_NAME )
	
	NSString *sourceListSelection = [[sourceListTreeController selection] valueForKey:@"sourceItemType"];
	
	if ( [sourceListSelection isEqualToString:@"VIEW_ALL_ASSIGNMENTS_LIST"] ) 
	{
		NSLog(@"[ATXCoreController] From Selection Item Type deduce selection is All Assignments");
		
		 //NSLog(@"current assignments has %i objects",[currentAssignments count]);
		 [assignmentsTableController setFilterPredicate:nil];

	} 
	else if ( [sourceListSelection isEqualToString:@"VIEW_COURSE_WITH_NAME"] )
	{
		NSMutableString *courseString = [[sourceListTreeController selection] valueForKey:@"trueName"];
		
		NSPredicate *fp = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"course.name contains[c] '%@'",courseString]];
		[assignmentsTableController setFilterPredicate:fp];
		
		//NSLog(@"current assignments has %i objects",[currentAssignments count]);
		//[self setTheCurrentAssignments:fetchResults];
		
	} else {
		NSLog(@"didn't select any of them");
	}
}

- (IBAction)setAssignmentsAsUneditable:(id)sender
{
	[assignmentsTableController setEditable:NO];
}

#pragma mark -
#pragma mark Add-Remove Assignments (and Releated) Methods

/** addAssignment will check for the selected item in the sourcelist. If the "All Assignments"
    item is selected the method will perform a simple add:self on the assignments array controller.
	If a course is selected the method will manually insert a NSManagedObject into the context to avoid
    resetting the filter predicate for the array controller
*/
- (void)addAssignment
{
	NSMutableString *courseString = [[sourceListTreeController selection] valueForKey:@"trueName"];
	
	if ([courseString isEqualToString:@"All Assignments"]) {
	
		[assignmentsTableController add:self];
	}
	else {
		/* We are in a course view now - we need to insert the NSManagedObject manually
		vs using add on the NSArrayController because that evidently resets the filter predicate */
		NSManagedObject *newAssignment = [NSEntityDescription insertNewObjectForEntityForName:@"Assignment" 
																	   inManagedObjectContext:[self managedObjectContext]];
		
		//now we need to set the course 
		int courseIndex = [self getCoursesIndexWithName:courseString];
		
		//check to make sure courseIndex isn't -1 (ERROR)
		if ( courseIndex != -1 ) {
			//Johnny Johnny says everythings cool so lets go on now that we know we have a good value
			[newAssignment setValue:[[coursesController arrangedObjects] objectAtIndex:courseIndex]
							 forKey:@"course"];
		} else {
			
			NSLog(@"[ATXCoreController] ERROR: Course Index not found in getCoursesIndexWithName method!");
			
			//somehow we reached this point so basically we'll not set the course value and 
			//continue on our merry little way 
		}

		//int scou = [[assignmentsTableController arrangedObjects] count];
		[assignmentsTableController setSelectedObjects:[NSArray arrayWithObject:newAssignment]];
		//[assignmentsTableController setSelectionIndex:(scou - 1)];
		//[assignmentsTableView selectRow:(scou - 1) byExtendingSelection:NO];
		//[assignmentsTableView selectRow: byExtendingSelection:<#(BOOL)extend#>
	} 
}

/** returns the integer index of the course with a name if sucessfull,
    otherwise returns -1 for an error
    @param courseSearchString name of course you are searching for
*/
- (int)getCoursesIndexWithName:(NSString *)courseSearchString
{
	int ci;
	for (ci = 0; ci < [[coursesController arrangedObjects] count]; ci++) 
	{
		NSManagedObject *courseSearchItem = [[coursesController arrangedObjects] objectAtIndex:ci];
		if ([[courseSearchItem valueForKey:@"name"] isEqualToString:courseSearchString]) {
			return ci;
		}
	}
	return -1;
}

/** Simply call remove:self on assignment array controller */
- (void)deleteAssignment
{
	//need to take user preferences into account
	if ([defaults boolForKey:@"WARNING Delete Assignments"] == YES) {
		int result = NSRunAlertPanel(@"Are you sure you want to delete this assignment?",
		@"",
		@"OK",
		@"Cancel",
		nil);
		if (result == NSOKButton)
		{
			[assignmentsTableController removeObjects:[assignmentsWrapperController selectedObjects]];
		}
	} else {
		[assignmentsTableController removeObjects:[assignmentsWrapperController selectedObjects]];
	}
}

#pragma mark -

@end

@implementation ATXCoreController (SetupUtilities)

- (void)finishInitializingSetup
{
	/* Setup the Categories, Priorities and go through the courses
	 * to add them to the source list */
	lastUniqueId = 10; //setup unique id for the source list items
	[defaults setBool:YES forKey:ATX_RETURN_FROM_STARTUPWIZARD_COMPLETE];
	
	[self setupGenericCategories];
	[self setupAssignmentPriorities];
	[self setupAssignmentStatuses];
	[self setupInitialUserDefaults];
	[self setupInitialSourceList];
}

- (void)setupInitialUserDefaults;
{
	[defaults setInteger:10 forKey:LAST_UNIQUE_SOURCELIST_ID];
}

- (void)setupInitialSourceList
{	
	/* Setup the Static List Item(s) */
	NSManagedObject *firstItem = [[sourceList newObject] autorelease];
	
	[firstItem setValue:@"All Assignments" 
				 forKey:@"name"];
	[firstItem setValue:@"All Assignments" 
				 forKey:@"trueName"];
	[firstItem setValue:@"edit-classes16" 
				 forKey:@"icon"];
	[firstItem setValue:NO forKey:@"areDropsAccepted"];
	[firstItem setValue:[NSNumber numberWithInt:lastUniqueId] 
				 forKey:@"position"];
	[firstItem setValue:@"VIEW_ALL_ASSIGNMENTS_LIST" 
				 forKey:@"sourceItemType"];
	
	[sourceList addObject:firstItem];
	
	/* increment the position count by 10 */
#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Assigned Unique ID %i to source list item \"All Assignments\"",lastUniqueId);
#endif
	[self incrementTheUniqueID];
	
#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Created Source List Item All Assignments");
#endif
	
	/* Setup the Course sourcelist items  */
	NSEnumerator *coursesEnumerator = [[coursesController arrangedObjects] objectEnumerator];
	NSManagedObject *courseObject;
	while((courseObject = [coursesEnumerator nextObject])) 
	{
		NSManagedObject *courseSourceListItem = [[sourceList newObject] autorelease];
		
		[courseSourceListItem setValue:[courseObject valueForKey:@"name"]
								forKey:@"name"];
		[courseSourceListItem setValue:[courseObject valueForKey:@"name"]
								forKey:@"trueName"];
		[courseSourceListItem setValue:NO 
								forKey:@"areDropsAccepted"];
		[courseSourceListItem setValue:@"booksmall16" 
								forKey:@"icon"];
		[courseSourceListItem setValue:[NSNumber numberWithInt:lastUniqueId]
								forKey:@"position"];
		[courseSourceListItem setValue:@"VIEW_COURSE_WITH_NAME"
								forKey:@"sourceItemType"];
		
		[sourceList addObject:courseSourceListItem];
		
		[self incrementTheUniqueID];
#ifdef VERBOSE_MODE
		NSLog(@"[ATXCoreController] Added Course %@ to the Source List!",[courseObject valueForKey:@"name"]);
#endif
	}
}

- (void)setupGenericCategories
{
	/* One time setup method that is only executed during the first time setup
	 * for each document 
	 ***************************************************************************
	 * Need to setup the 3 Generic Categories
	 * (1) Assignment
	 * (2) Quiz
	 * (3) Test
	 ***************************************************************************
     * GenericCategory Entity only has 1 Attribute and 1 Relationship
	 * ( Attribute ) name is String
	 * ( Relationship ) assignment is a To Many relationship
	 */
	
	if([genericCategoriesController isEditable] == NO)
	{
		[genericCategoriesController setEditable:YES];
	}
	
	NSManagedObject *assignmentCategory = [[genericCategoriesController newObject] autorelease];
	[assignmentCategory setValue:@"Assignment" forKey:@"name"];
	[assignmentCategory setValue:[NSNumber numberWithInt:10] forKey:@"position"];
	[genericCategoriesController addObject:assignmentCategory];
	
#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Created Generic Category: Assignment");
#endif
	
	NSManagedObject *quizCategory = [[genericCategoriesController newObject] autorelease];
	[quizCategory setValue:@"Quiz" forKey:@"name"];
	[quizCategory setValue:[NSNumber numberWithInt:20] forKey:@"position"];
	[genericCategoriesController addObject:quizCategory];

#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Created Generic Category: Quiz");
#endif
	
	NSManagedObject *testCategory = [[genericCategoriesController newObject] autorelease];
	[testCategory setValue:@"Test" forKey:@"name"];
	[testCategory setValue:[NSNumber numberWithInt:30] forKey:@"position"];
	[genericCategoriesController addObject:testCategory];
	
#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Created Generic Category: Test");
#endif
	
	//Well we'll just have to clean this mess up! - Lala
	NSSortDescriptor *cdes = [[NSSortDescriptor alloc] initWithKey:@"position"
														 ascending:YES];
	[genericCategoriesController setSortDescriptors:[NSArray arrayWithObject:cdes]];
	
	[cdes release];
	
	[genericCategoriesController setEditable:NO];
}

- (void)setupAssignmentPriorities;
{
	/* This is another one time setup method only used to setup the assignment priorities
	 * which can be used to */
	NSManagedObject *veryHighPriority = [[assignmentsPrioritiesController newObject] autorelease];
	[veryHighPriority setValue:@"Very High" forKey:@"name"];
	[veryHighPriority setValue:[NSNumber numberWithInt:10] forKey:@"position"];
#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Setup Assignment Priority \"Very High\"");
#endif
	
	NSManagedObject *highPriority = [[assignmentsPrioritiesController newObject] autorelease];
	[highPriority setValue:@"High" forKey:@"name"];
	[highPriority setValue:[NSNumber numberWithInt:20] forKey:@"position"];
#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Setup Assignment Priority \"High\"");
#endif
	
	NSManagedObject *mediumPriority = [[assignmentsPrioritiesController newObject] autorelease];
	[mediumPriority setValue:@"Medium" forKey:@"name"];
	[mediumPriority setValue:[NSNumber numberWithInt:30] forKey:@"position"];
#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Setup Assignment Priority \"Medium\"");
#endif
	
	NSManagedObject *lowPriority = [[assignmentsPrioritiesController newObject] autorelease];
	[lowPriority setValue:@"Low" forKey:@"name"];
	[lowPriority setValue:[NSNumber numberWithInt:40] forKey:@"position"];
#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Setup Assignment Priority \"Low\"");
#endif
	
	NSManagedObject *veryLowPriority = [[assignmentsPrioritiesController newObject] autorelease];
	[veryLowPriority setValue:@"Very Low" forKey:@"name"];
	[veryLowPriority setValue:[NSNumber numberWithInt:50] forKey:@"position"];
#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Setup Assignment Priority \"Very Low\"");
#endif
	
	NSSortDescriptor *stsort = [[NSSortDescriptor alloc] initWithKey:@"position"
														   ascending:YES];
	[assignmentsPrioritiesController setSortDescriptors:[NSArray arrayWithObject:stsort]];
	
	[stsort release];
}

- (void)setupAssignmentStatuses
{
	NSManagedObject *incomplete = [[assignmentStatusController newObject] autorelease];
	[incomplete setValue:@"Incomplete" forKey:@"name"];
	[incomplete setValue:[NSNumber numberWithInt:10] forKey:@"position"];
#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Setup Assignment Status \"Incomplete\"");
#endif
	
	NSManagedObject *partiallyComplete = [[assignmentStatusController newObject] autorelease];
	[partiallyComplete setValue:@"Partially Complete" forKey:@"name"];
	[partiallyComplete setValue:[NSNumber numberWithInt:20] forKey:@"position"];
#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Setup Assignment Status \"Partially Complete\"");
#endif
	
	NSManagedObject *awaitingGrade = [[assignmentStatusController newObject] autorelease];
	[awaitingGrade setValue:@"Awaiting Grade" forKey:@"name"];
	[awaitingGrade setValue:[NSNumber numberWithInt:30] forKey:@"position"];
#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Setup Assignment Status \"Awaiting Grade\"");
#endif
	
	NSManagedObject *complete = [[assignmentStatusController newObject] autorelease];
	[complete setValue:@"Complete" forKey:@"name"];
	[complete setValue:[NSNumber numberWithInt:40] forKey:@"position"];
#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Setup Assignment Status \"Complete\"");
#endif
	
	NSManagedObject *dropped = [[assignmentStatusController newObject] autorelease];
	[dropped setValue:@"Dropped" forKey:@"name"];
	[dropped setValue:[NSNumber numberWithInt:50] forKey:@"position"];
#ifdef VERBOSE_MODE
	NSLog(@"[ATXCoreController] Setup Assignment Status \"Dropped\"");
#endif
	
	NSSortDescriptor *ssort = [[NSSortDescriptor alloc] initWithKey:@"position" 
														  ascending:YES];
	[assignmentStatusController setSortDescriptors:[NSArray arrayWithObject:ssort]];
	[ssort release];
}

@end

@implementation ATXCoreController (Toolbar)

-(BOOL)validateToolbarItem:(NSToolbarItem *)toolbarItem
{
	if (([[toolbarItem itemIdentifier] isEqualToString:@"ADD_ASSIGNMENT"] ||
		[[toolbarItem itemIdentifier] isEqualToString:@"DELETE_ASSIGNMENT"]) && 
		[defaults boolForKey:ATX_RETURN_FROM_STARTUPWIZARD_COMPLETE] == NO) {
		return NO;
	}
	return YES;
}

- (NSArray *)toolbarAllowedItemIdentifiers:(NSToolbar *)toolbar
{
	return [NSArray arrayWithObjects:@"ADD_ASSIGNMENT",
		@"DELETE_ASSIGNMENT",
		@"SEARCH_VIEW",
		NSToolbarCustomizeToolbarItemIdentifier,
		NSToolbarFlexibleSpaceItemIdentifier,
		NSToolbarSpaceItemIdentifier,
		nil];
}

- (NSArray *)toolbarDefaultItemIdentifiers:(NSToolbar *)toolbar
{
	return [NSArray arrayWithObjects:@"ADD_ASSIGNMENT",
		@"DELETE_ASSIGNMENT",
		NSToolbarFlexibleSpaceItemIdentifier,
		@"SEARCH_VIEW",nil];
}

- (NSToolbarItem *)toolbar:(NSToolbar *)toolbar
	 itemForItemIdentifier:(NSString *)itemIdentifier
 willBeInsertedIntoToolbar:(BOOL)flag
{
	NSToolbarItem *item = [[NSToolbarItem alloc] initWithItemIdentifier:itemIdentifier];
	
	if ( [itemIdentifier isEqualToString:@"ADD_ASSIGNMENT"] )
	{
		[item setLabel: NSLocalizedString( @"Add", nil ) ];
		[item setPaletteLabel: [ item label ] ];
		[item setImage: [ NSImage imageNamed: @"newAsn.tif" ] ];
		[item setTarget:self];
		[item setAction:@selector(addAssignment)];
		
    } else if ( [itemIdentifier isEqualToString:@"DELETE_ASSIGNMENT"] ) {
		[item setLabel: NSLocalizedString( @"Delete", nil ) ];
		[item setPaletteLabel: [ item label ] ];
		[item setImage: [ NSImage imageNamed: @"AsnDelete.tif" ] ];
		[item setTarget:self];
		[item setAction:@selector(deleteAssignment)];
		
	} else if ( [itemIdentifier isEqualToString:@"SEARCH_VIEW"] ) {
		
		NSRect searchRect = [toolbarSearchView frame];
		[item setLabel: NSLocalizedString(@"", nil) ];
		[item setPaletteLabel:[item label]];
		[item setView:toolbarSearchView];
		[item setMinSize:searchRect.size];
		[item setMaxSize:searchRect.size];
	}
	
    return [ item autorelease ];
}

@end
