//
//  Student.m
//  Lab1c
//
//  Created by R.J. Aquino on 7/7/13.
//  Copyright (c) 2013 CS50. All rights reserved.
//

#import "Student.h"

@implementation Student

/*
 * Init method
 */
- (Student *)init {
    self = [super init];
    
    // initialize major to undeclared
    self.major = @"Undeclared";
    
    // initialize NSMutableDictionary for grades
    self.grades = [[NSMutableDictionary alloc] init];
    return self;
}

/*
 * Legacy name method. Returns full name.
 */
- (NSString*)name {
    return [NSString stringWithFormat:@"%@ %@", self.first_name, self.last_name];
}

/*
 * Overwritten setMajor to enfoce valid majors only.
 */
- (void)setMajor:(NSString *)major {
    // get valid majors
    NSArray *majors = [Student validMajors];
    
    // check if requested major is valid
    if ([majors containsObject:major])
        _major = [major copy];
    else
        NSLog(@"%@ is not a valid major. %@'s major is still %@", major, self.name, self.major);
}

/*
 * Returns the valid majors
 */
+ (NSArray *)validMajors {
    NSArray *majors = [[NSArray alloc] initWithObjects:@"Math", @"English", @"Computer Science", @"Undeclared",  nil];
    return majors;
}

/*
 * Over written description method (the description method of an NSObject is secretly what's called when you print or NSLog "%@".
 */
- (NSString*)description {
    // get last two digits from year
    int trimmed_year = self.year % 1000 % 100;
    
    // return string (%02d means that years like 2004 will come out 04, up to two digits, padded with zeroes)
    return [NSString stringWithFormat:@"%@ '%02d, %@", self.name, trimmed_year, self.major];
}

/*
 * Legacy method for age, using birthday property
 */
- (int)age {
   
    // use the NSCalendar methods for date math
    // see http://stackoverflow.com/questions/4739483/number-of-days-between-two-nsdates  and
    // http://cocoamatic.blogspot.com/2010/09/nsdate-number-of-days-between-two-dates.html for more details
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSUInteger unitFlags = NSYearCalendarUnit;
    NSDateComponents *components = [calendar components:unitFlags fromDate:self.birthday toDate:[NSDate date] options:0];
    
    
    return (int)[components year];
}

/*
 * Instance method for adding a grade. We could do this directly in main.m, but if we ever changed
 * how grades were stored, we'd have to change every line that added a grade.
 */
- (void)addGradeForClass:(int)classNum WithGrade:(int)grade {
    [self.grades setValue:[NSNumber numberWithInt:grade] forKey:[NSString stringWithFormat:@"%d", classNum]];
}
@end
