/* Copyright (c) 2011 Artjom Popov */

#import "NSDate+Additions.h"

NSDateFormatter *NSGetSQLDateFormatter()
{
	static NSDateFormatter *dateFormatter = nil;
	
	if(!dateFormatter) {
		dateFormatter = [[NSDateFormatter alloc] init];
		[dateFormatter setDateFormat:@"yyyy-MM-dd"];
	}
	
	return dateFormatter;
}

NSDateFormatter *NSGetSQLDateTimeFormatter()
{
	static NSDateFormatter *dateFormatter = nil;
	
	if(!dateFormatter) {
		dateFormatter = [[NSDateFormatter alloc] init];
		[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
	}
	
	return dateFormatter;
}

NSDateFormatter *NSGetDateTimeFormatter()
{
	static NSDateFormatter *dateFormatter = nil;
	
	if(!dateFormatter) {
		dateFormatter = [[NSDateFormatter alloc] init];
		[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
	}
	
	return dateFormatter;
}

@interface NSObject(NSDateHacks)

- (NSString *)descriptionWithCalendarFormat:(NSString *)format timeZone:(NSTimeZone *)timeZone locale:(NSLocale *)locale;

@end

@implementation NSObject(NSDateHacks)

- (NSString *)descriptionWithCalendarFormat:(NSString *)format timeZone:(NSTimeZone *)timeZone locale:(NSLocale *)locale
{
	return @"###ERROR###";
}

@end

#pragma mark -

@implementation NSDate(Additions)

- (NSString *)descriptionWithCalendarFormat:(NSString *)format
{
	// FIXME: Apple doesn't recommend this use this method, but unfortunately doesn't provide a easily workable alternative. And yes, NSDateFormatter is broken.
	return [self descriptionWithCalendarFormat:format timeZone:nil locale:[NSLocale currentLocale]];
}

@dynamic stringValue;

- (NSString *)stringValue
{
	return [self descriptionWithCalendarFormat:@"%H:%M:%S %m/%d/%Y"];
}

@dynamic sqlDateTimeStringValue;

- (NSString *)sqlDateTimeStringValue
{
	NSString *date = [NSGetSQLDateTimeFormatter() stringFromDate:self];
	
	return (date) ? date : [NSGetSQLDateFormatter() stringFromDate:self];
}

@dynamic soapDateTimeStringValue;

- (NSString *)soapDateTimeStringValue
{
	return [NSGetDateTimeFormatter() stringFromDate:self];
}

- (NSString *)timeLeftSinceNow
{
	NSTimeInterval seconds = [self timeIntervalSinceNow];
	
	int days = (int)floor(seconds / 84000);
	int hours = (int)floor((seconds - (days * 84000)) / 3600);
	int minutes = (int)floor((seconds - (days * 84000) - (hours * 3600)) / 60);

	return [NSString stringWithFormat:NSLocalizedString(@"TimeLeft.Format", nil), hours, minutes];
}

@end
