/*
**  IMAPCacheManager.m
**
**  Copyright (c) 2001, 2002, 2003
**
**  Author: Ludovic Marcotte <ludovic@Sophos.ca>
**
**  This library is free software; you can redistribute it and/or
**  modify it under the terms of the GNU Lesser General Public
**  License as published by the Free Software Foundation; either
**  version 2.1 of the License, or (at your option) any later version.
**  
**  This library is distributed in the hope that it will be useful,
**  but WITHOUT ANY WARRANTY; without even the implied warranty of
**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
**  Lesser General Public License for more details.
**  
**  You should have received a copy of the GNU Lesser General Public
**  License along with this library; if not, write to the Free Software
**  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/

#include <Pantomime/IMAPCacheManager.h>

#include <Pantomime/Constants.h>
#include <Pantomime/IMAPMessage.h>

#include <Foundation/NSArchiver.h>
#include <Foundation/NSException.h>
#include <Foundation/NSValue.h>

static int currentIMAPCacheManagerVersion = 3;

//
//
//
@implementation IMAPCacheManager

- (id) init
{
  self = [super init];
  
  [IMAPCacheManager setVersion: currentIMAPCacheManagerVersion];
  
  hash = [[NSMutableDictionary alloc] init];

  [self setUIDValidity: 0];
  [self setCache: [NSArray array]];
 
  return self;
}


//
//
//
- (id) initWithPath: (NSString *) thePath
{
  self = [self init];
  
  [self setPathToCache: thePath];

  return self;
}


//
//
//
- (void) dealloc
{
  RELEASE(pathToCache);
  RELEASE(cache);
  RELEASE(hash);

  [super dealloc];
}


//
//
//
- (BOOL) synchronize
{
  BOOL b;

  NS_DURING
    {
      b = [NSArchiver archiveRootObject: self
		      toFile: [self pathToCache]];
    }
  NS_HANDLER
    {
      NSLog(@"Failed to synchronize the %@ IMAP cache. Not written to disk.", [self pathToCache]);
      b = NO;
    }
  NS_ENDHANDLER
    
  return b;
}


//
// NSCoding protocol
//
- (void) encodeWithCoder: (NSCoder *) theCoder
{
  [IMAPCacheManager setVersion: currentIMAPCacheManagerVersion];
   
  [theCoder encodeObject: [NSNumber numberWithInt: [self UIDValidity]] ];
  [theCoder encodeObject: [self cache]];
}


//
//
//
- (id) initWithCoder: (NSCoder *) theCoder
{
  int version;
  
  version = [theCoder versionForClassName: NSStringFromClass([self class])];
  
  self = [super init];

  hash = [[NSMutableDictionary alloc] init];

  if ( version < currentIMAPCacheManagerVersion )
    {
      // We do nothing, so the cache will be entirely reloaded
      [NSException raise: NSInternalInconsistencyException
		   format: @"IMAP cache error."];
    }
  else
    {
      [self setUIDValidity: [[theCoder decodeObject] intValue]];
      [self setCache: [theCoder decodeObject]];
    }

  return self;
}


//
// access/mutation methods
//
- (void) addMessage: (IMAPMessage *) theIMAPMessage
{
  [hash setObject: theIMAPMessage  forKey: [NSNumber numberWithInt: [theIMAPMessage UID]]];
  [cache addObject: theIMAPMessage];
}


//
//
//
- (void) removeMessage: (IMAPMessage *) theIMAPMessage
{
  [hash removeObjectForKey: [NSNumber numberWithInt: [theIMAPMessage UID]]];
  [cache removeObject: theIMAPMessage];
}


//
//
//
- (IMAPMessage *) messageWithUID: (int) theUID
{
  return [hash objectForKey: [NSNumber numberWithInt: theUID]];
}


//
//
//
- (NSMutableArray *) cache
{
  return cache;
}


//
//
//
- (void) setCache: (NSArray *) theCache
{
  if ( theCache )
    {
      NSMutableArray *aMutableArray;
      int i;

      aMutableArray = [[NSMutableArray alloc] initWithArray: theCache];
      RELEASE(cache);
      cache = aMutableArray;

      // We populate our hashtable
      for (i = 0; i < [cache count]; i++)
	{
	  [hash setObject: [cache objectAtIndex: i]
		forKey: [NSNumber numberWithInt: [[cache objectAtIndex: i] UID]]];
	}
    }
  else
    {
      DESTROY(cache);
    }
}


//
//
//
- (NSString *) pathToCache
{
  return pathToCache;
}


//
//
//
- (void) setPathToCache: (NSString *) thePathToCache
{
  if ( thePathToCache )
    {
      RETAIN(thePathToCache);
      RELEASE(pathToCache);
      pathToCache = thePathToCache;
    }
  else
    {
      DESTROY(pathToCache);
    }
}


//
//
//
- (int) UIDValidity
{
  return UIDValidity;
}

//
//
//
- (void) setUIDValidity: (int) theUIDValidity
{
  UIDValidity = theUIDValidity;
}


//
//
//
- (void) flush
{
  [cache removeAllObjects];
  [self setUIDValidity: 0];
  [self synchronize];
}


//
// class methods
//
+ (id) cacheFromDiskWithPath: (NSString *) thePath;
{
  IMAPCacheManager *theIMAPCacheManager;
  
  NS_DURING
    theIMAPCacheManager = [NSUnarchiver unarchiveObjectWithFile: thePath];
  NS_HANDLER
    NSLog(@"Caught exception while unarchiving the IMAP cache. Ignoring the cache.");
    theIMAPCacheManager = nil;
  NS_ENDHANDLER

  if ( theIMAPCacheManager )
    {
      [theIMAPCacheManager setPathToCache: thePath];
    }
  else
    {
      theIMAPCacheManager = [[IMAPCacheManager alloc] initWithPath: thePath];
      AUTORELEASE(theIMAPCacheManager);
    }

  return theIMAPCacheManager;
}

@end
