//
//  tImageBuffer.m
//  Hootenanny
//
//  Created by Noah Sorscher on Sun Mar 30 2003.
//  Copyright (c) 2003 __MyCompanyName__. All rights reserved.
//

#import "tImageBuffer.h"


@implementation tImageBuffer


- (tImageBuffer *)init
{
    theImages = [[NSMutableDictionary alloc] init];
    anchor = [[NSMutableDictionary alloc] init];
    [anchor setObject:anchor forKey:@"next"];
    [anchor setObject:anchor forKey:@"prev"];
    maxImages = 500;
    currentSize = 0;
    self = [super init];
    return self;
}

- (void)setMaxSize:(long)numImages
{
    maxImages = numImages;
    while (currentSize > maxImages)
        [self pop];
}

- (void)setImage:(NSImage *)anImage forIndex:(long)index
{
    if (nil == anImage) return;
    NSMutableDictionary *buffer = nil;
    buffer = [theImages objectForKey:[NSNumber numberWithLong:index]];
    if (buffer != nil)
        [self removeObject:buffer];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setObject:anImage forKey:@"image"];
    [dict setObject:[NSNumber numberWithLong:index] forKey:@"index"];
    [self push:dict];
    currentSize++;
    if (currentSize > maxImages)
        [self removeObject:[anchor objectForKey:@"prev"]];
}

- (NSImage *)imageForIndex:(long)index
{
    NSMutableDictionary *theObject = [theImages objectForKey:[NSNumber numberWithLong:index]];
    if (nil == theObject) return nil;
    [self extractObject:theObject];
    [self push:theObject];
    return [theObject objectForKey:@"image"];
}

- (void)removeObject:(NSDictionary *)dict
{
    [self extractObject:dict];
    [dict release];
    currentSize--;
}

- (void)extractObject:(NSDictionary *)dict
{
    NSMutableDictionary *next, *prev;
    next = [dict objectForKey:@"next"];
    prev = [dict objectForKey:@"prev"];
    [prev setObject:next forKey:@"next"];
    [next setObject:prev forKey:@"prev"];
}

- (void)push:(NSMutableDictionary *)dict
{
    NSMutableDictionary *next, *prev;
    next = [anchor objectForKey:@"next"];
    prev = anchor;
    
    [prev setObject:dict forKey:@"next"];
    
    [dict setObject:next forKey:@"next"];
    [dict setObject:prev forKey:@"prev"];
    
    [next setObject:dict forKey:@"prev"];
    [theImages setObject:dict forKey:[dict objectForKey:@"index"]];
}

- (void)pop
{
    if (currentSize == 0) return;
    NSDictionary *theObject = [anchor objectForKey:@"prev"];
    [theImages removeObjectForKey:[theObject objectForKey:@"index"]];
    [self removeObject:theObject];
}

- (void)empty
{
    NSDictionary *dict;
    NSArray *keys = [theImages allKeys];
    int i, n = [keys count];
    for (i=0; i<n; i++) {
        dict = [theImages objectForKey:[keys objectAtIndex:i]];
        [theImages removeObjectForKey:[keys objectAtIndex:i]];
        [dict release];
    }
    currentSize = 0;
    [anchor setObject:anchor forKey:@"next"];
    [anchor setObject:anchor forKey:@"prev"];
}

@end
