#include "CacheEngine.h"

#include <Foundation/NSNull.h>
#include <Foundation/NSDictionary.h>

@implementation CacheEngine

-(id) init
{
  if ( ! ( self = [super init] ) )
    return nil;

  _backend = [[NSMutableDictionary alloc]  init];
  
  return self;
      
}

+ (void)connectWithPorts:(NSArray *)portArray
{
  NSAutoreleasePool *pool;
  NSConnection *serverConnection;
  CacheEngine *serverObject;

  pool = [[NSAutoreleasePool alloc] init];
  serverConnection = [NSConnection
		       connectionWithReceivePort:[portArray objectAtIndex:0]
		       sendPort:[portArray objectAtIndex:1]];

  serverObject = [[self alloc] init];
  
  [(id)[serverConnection rootProxy] setServer:serverObject];
  

  [serverObject release];
  [[NSRunLoop currentRunLoop] run];

  [pool release];
}


-(void) dealloc
{
  if ( _backend ) 
    [_backend release];
  [super dealloc];
}

-(void) addImagePaths: (NSArray *) paths
{
  if ( ! paths ) 
    return;

 {
   unsigned int i,count= [paths count];
   
   for ( i=0;i<count;i++)
     {
#warning check path ? 
       [_backend setObject:[NSNull null] forKey:[paths objectAtIndex:i]];
     }
 }

}


-(void) removePath:(NSString *) path
{
#warning check exception !! 
  [_backend removeObjectForKey: path];
}


-(NSData *) imageForPath:(NSString *) path
{
#warning check exception 
  if ( [_backend objectForKey:path] == [NSNull null] ) 
    {
      [_backend setObject:[[NSData alloc] initWithContentsOfFile:path] forKey:path];
    }

  NSLog(@"RETURN %@ for path %@",NSStringFromClass([[_backend objectForKey:path] class]),path);
  return [_backend objectForKey:path];
}


-(void) userUsePath: (NSString *) path
{
  NSEnumerator *enumerator = [_backend keyEnumerator];
  id key;
  unsigned int i = 0;

  while ( ( key = [enumerator nextObject] ) || ( i < 10 ) ) 
    {

      if ( [_backend objectForKey:key] == [NSNull null] ) 
	{
	  NSLog(@"add %@",key);
	  [_backend setObject:[[NSData alloc] initWithContentsOfFile:key] forKey:key];
	}
      i++;
    }
}


@end
