//  NSDate+CalendarHelpers.mm

#import "NSDate+CalendarHelpers.h"

@implementation NSDate (CalendarHelpers)

- (NSCalendar *)_calendar {
    static NSCalendar *cal;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        cal = [NSCalendar currentCalendar];
        cal.timeZone = [NSTimeZone systemTimeZone];
    });
    return cal;
}

- (NSDate *)startOfMonth {
    NSCalendar *cal = [self _calendar];
    NSDateComponents *comps = [cal components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:self];
    comps.day = 1;
    return [cal dateFromComponents:comps];
}

- (NSDate *)endOfMonth {
    NSCalendar *cal = [self _calendar];
    NSDateComponents *comps = [cal components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:self];
    comps.month += 1;
    comps.day = 0;
    return [cal dateFromComponents:comps];
}

- (NSInteger)numberOfDaysInMonth {
    NSCalendar *cal = [self _calendar];
    NSRange r = [cal rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:self];
    return r.length;
}

- (NSInteger)weekdayOfFirstDay {
    NSCalendar *cal = [self _calendar];
    NSDate *start = [self startOfMonth];
    NSDateComponents *c = [cal components:NSCalendarUnitWeekday fromDate:start];
    return c.weekday;
}

- (NSDate *)dateByAddingMonths:(NSInteger)months {
    NSCalendar *cal = [self _calendar];
    NSDateComponents *c = [[NSDateComponents alloc] init];
    c.month = months;
    return [cal dateByAddingComponents:c toDate:self options:0];
}

- (BOOL)isSameDayAsDate:(NSDate *)otherDate {
    NSCalendar *cal = [self _calendar];
    NSDateComponents *a = [cal components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:self];
    NSDateComponents *b = [cal components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:otherDate];
    return (a.year == b.year && a.month == b.month && a.day == b.day);
}

- (NSString *)yyyyMMddString {
    static NSDateFormatter *fmt;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"yyyy-MM-dd";
        fmt.timeZone = [NSTimeZone systemTimeZone];
    });
    return [fmt stringFromDate:self];
}

@end

