// 
//  Student.m
//  StudentManager
//
//  Created by Richard Wicentowski on 2/23/11.
//  Copyright 2011 Swarthmore College. All rights reserved.
//

#import "Student.h"


@implementation Student 

@dynamic name;
@dynamic gradYear;
@dynamic majorDepartment;


+ (Student *)studentWithName:(NSString *)studentName year:(NSNumber *)year
	  inManagedObjectContext:(NSManagedObjectContext *)context
{
	Student *student = nil;
	
	NSFetchRequest *request = [[NSFetchRequest alloc] init];
	request.entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:context];
	NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"name = %@", studentName];
	NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"gradYear = %@", year];
	request.predicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:predicate1,
																			predicate2, nil]];

	NSError *error = nil;
	student = [[context executeFetchRequest:request error:&error] lastObject];
	
	if (!error && !student) {
		student = [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:context];
		student.name = studentName;
		student.gradYear = year;		
	}
	
	
	return student;
}


- (NSString *)sectionName {
	return [self.name substringToIndex:1];
}

- (NSString *)titleKey {
	return [NSString stringWithFormat:@"%@ (%@): %@", self.name, self.gradYear, self.majorDepartment.name];
}


@end
