#import <Foundation/Foundation.h>
#import "RNFileCacheTagManager.h"

@implementation RNFileCacheTagManager {
  NSString *path;
  NSNumber *saving;
}

- (id)initWithPath:(NSString *)_path
{
  if(self = [super init]) {
    path = _path;
  }
  return self;
}

- (NSMutableDictionary *)restore
{
  NSData *data = [NSData dataWithContentsOfFile:path];
  NSMutableDictionary *ret = (NSMutableDictionary*)[NSKeyedUnarchiver unarchiveObjectWithData:data];
  if(ret == nil) ret = [NSMutableDictionary dictionary];
  return ret;
}

- (void)save:(NSMutableDictionary *)tagMap
{
  @synchronized(saving) {
    if([saving boolValue] == YES) return;
    saving = [NSNumber numberWithBool:YES];
    NSMutableDictionary *storedMap = [NSMutableDictionary dictionaryWithDictionary:tagMap];
    // wait 1sec to save for avoiding too many time saving requests.
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(), ^{ 
      saving = [NSNumber numberWithBool:NO];
      NSData *data = [NSKeyedArchiver archivedDataWithRootObject:storedMap];
      [data writeToFile:path atomically: YES];
    });
  }
}


@end
