#import "NSDateEx.h"

@implementation NSDate (DateFormat)

static  NSMutableArray* _formats = nil;

+ (void)load
{
    NSAutoreleasePool*  pool;
    pool = [[NSAutoreleasePool alloc] init];
    
    if (!_formats) {
        _formats = [[NSMutableArray array] retain];
        
        // Add default formats
        [_formats addObject:@"%Y-%m-%dT%H:%M:%S%z"];
        [_formats addObject:@"%a, %d %b %Y %H:%M:%S %z"];
    }
    
    [pool release];
}

+ (NSArray*)dateFormats
{
    return [NSArray arrayWithArray:_formats];
}

+ (void)addDateFromatsWithContentsOfFile:(NSString*)filePath
{
    // Load file
    NSArray*    formats;
    formats = [NSArray arrayWithContentsOfFile:filePath];
    if (!formats) {
        // Warning
        NSLog(@"Can't load %@", filePath);
        return;
    }
    
    // Add formats
    [NSDate addDateFormats:formats];
}

+ (void)addDateFormats:(NSArray*)formats
{
    NSEnumerator*   enumerator;
    NSString*       format;
    enumerator = [formats objectEnumerator];
    while (format = [enumerator nextObject]) {
        if (![_formats containsObject:format]) {
            NSString*   copiedFormat;
            copiedFormat = [format copy];
            [_formats addObject:copiedFormat];
            [copiedFormat release];
        }
    }
}

+ (void)removeDateFormats:(NSArray*)formats
{
    [_formats removeObjectsInArray:formats];
}

+ (id)dateWithFormattedString:(NSString*)string
{
    // Remove ':' between HH and MM of time zone
    int     length;
    unichar colon, sign;
    length = [string length];
    colon = [string characterAtIndex:length - 3];
    sign = [string characterAtIndex:length - 6];
    if (colon == ':' && (sign == '-' || sign == '+')) {
        string = [NSString stringWithFormat:@"%@%@", 
                [string substringToIndex:length - 3], 
                [string substringFromIndex:length - 2]];
    }
    
    // Apply format
    NSEnumerator*   enumerator;
    NSString*       format;
    enumerator = [_formats objectEnumerator];
    while (format = [enumerator nextObject]) {
        NSCalendarDate* date;
        date = [NSCalendarDate dateWithString:string calendarFormat:format];
        if (date) {
            return date;
        }
    }
    
    // No proper format
    return nil;
}

+ (NSString*)formatForFormattedString:(NSString*)string
{
    // Apply format
    NSEnumerator*   enumerator;
    NSString*       format;
    enumerator = [_formats objectEnumerator];
    while (format = [enumerator nextObject]) {
        NSCalendarDate* date;
        date = [NSCalendarDate dateWithString:string calendarFormat:format];
        if (date) {
            return format;
        }
    }
    
    // No proper format
    return nil;
}

@end
