#import "DWIconCache.h"


@implementation DWIconCache

/* Initialization */

    + (id) instance16; {
        static DWIconCache* instance = nil;
        if (!instance) {
            instance = [[DWIconCache alloc] init];
            instance->width = 16;
        }
        return instance;
    }

    + (id) instance32; {
        static DWIconCache* instance = nil;
        if (!instance) {
            instance = [[DWIconCache alloc] init];
            instance->width = 32;
        }
        return instance;
    }
    
    - (id) init; {
        icons = [[NSMutableDictionary alloc] init];
        return self;
    }
    

/* API */

    - (DWCachedImage*) iconForFile: (NSString*) thePath; 
    {
        id img;
        if ((img = [icons objectForKey: thePath])) {
            return img;
        } else {
            id icon = [[NSWorkspace sharedWorkspace] iconForFile: [thePath stringByExpandingTildeInPath]];
            [icon setSize: (NSSize){width,width}];
            
            img = [[DWCachedImage alloc] initWithImage: icon];
            
            [icons setObject: img forKey: thePath];
            return img;
        }
    }

    - (DWCachedImage*) iconForExtension: (NSString*) extension; 
    {
        id img;
        if ((img = [icons objectForKey: extension])) {
            return img;
        } else {
            id icon = [[NSWorkspace sharedWorkspace] iconForFileType: extension];
            [icon setSize: (NSSize){width,width}];
            
            img = [[DWCachedImage alloc] initWithImage: icon];
            
            [icons setObject: img forKey: extension];
            return img;
        }
    }

    - (DWCachedImage*) iconForFilePath: (NSString*) thePath; {
        id extension = [thePath pathExtension];
        if (!extension || [extension isEqual: @""]) {
            return [self iconForFile: thePath];
        } else {
            return [self iconForExtension: extension];
        }
    }

@end