#import "Finch-Decoder.h"
#import "Finch-Reporter.h"

static NSMutableDictionary *decoders = nil;

@implementation FinchDecoder

#pragma mark Decoders

+ (void) registerDecoder: (Class) c forExtension: (NSString*) ext
{
    if (!decoders)
        decoders = [[NSMutableDictionary alloc] init];
    NSAssert2(![decoders objectForKey:ext],
        @"There is already a decoder for ”%@“: %@.",
        ext, [decoders objectForKey:ext]);
    [decoders setObject:c forKey:ext];
}

+ (FinchSample*) decodeFile: (NSString*) path error: (NSError**) error
{
    NSAssert([self class] == [FinchDecoder class],
        @"Decoder subclasses have to override this method.");
    
    // Find suitable decoder
    for (NSString *extension in [decoders allKeys])
        if ([path hasSuffix:extension])
            return [[decoders objectForKey:extension]
                decodeFile:path error:error];
    
    // No decoder found
    FinchReporter *reporter = [FinchReporter forDomain:@"Sample Decoder" error:error];
    *error = [reporter errorWithCode:kDENoSuitableDecoderFound description:
        [NSString stringWithFormat:@"No suitable decoder found for %@.", path]];
    return nil;
}

@end