#import "DWColor.h"
#import "DWTableString.h"
#import "NSAttributedStringExtensions.h"


DWTableString* DWTableStringCreate(NSString* theString, NSDictionary* theAttributes) {
    return [[DWTableString alloc] initWithString: theString attributes: theAttributes];
}

DWTableString* DWTableStringCreateCached(NSString* theString, NSDictionary* theAttributes) 
{
    /* cache */

        static id cache = nil;
        if (!cache) cache = [[NSMutableDictionary alloc] init];
    
        if ([cache count] > 300) {
            [cache removeAllObjects];
        }
        
    /* hit */
    
        id obj;
        if ((obj = [cache objectForKey: theString])) {
            return [obj retain];
        }
        
    /* miss */

        obj = DWTableStringCreate(theString, theAttributes);
        [cache setObject: obj forKey: theString];

        //NSLog(@"- (%i) %@", [cache count], theString);

    return obj;
}


@implementation DWTableString

/* Initialization */

    - (id) init; {
        self = [super init];
        [self setAlternateColor: [DWColor whiteColor]];
        return self;
    }
    
    - (void) dealloc; {
        [alternateString release];
        [super dealloc];
    }


/* Alternates */

    - (void) setAlternateColor: (NSColor*) theColor; {
        if (![theColor isEqual: alternateColor]) {
            [alternateString release];
            alternateString = nil;
            alternateColor = theColor;
        }
    }

    - (DWConfinedString*) alternateString; {
        if (alternateColor) {
            if (!alternateString) {
                alternateString = [[DWTableString alloc] initWithAttributedString: [string attributedStringWithColor: alternateColor]];
                [alternateString setStyle: style];
            }
            return alternateString;
        } else {
            return self;
        }
    }

@end