/* Copyright (c) 2011 Artjom Popov */


#import "UTHistoryManager.h"
#import "UTHistoryStory.h"

#define FILE_TO_SAVE @"History.plist"

NSString *UTHistoryManagerDidChangeNotification = @"UTHistoryManagerDidChangeNotification";

@implementation UTHistoryManager

+ (UTHistoryManager *)sharedManager
{
	static UTHistoryManager *sharedManager = nil;
	
	if(!sharedManager) {
		sharedManager = [[UTHistoryManager alloc] init];
	}
	
	return sharedManager;
}

@synthesize stories = m_stories;

- (BOOL)containsStory:(UTHistoryStory *)story
{
	if(!story) return NO;
	return [self->m_stories containsObject:story];
}

- (void)saveStories
{
	NSMutableArray *stories = [NSMutableArray array];
	for(UTHistoryStory *story in self->m_stories) {
		[stories addObject:story.id];
	}
	
	[stories writeToFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] 
							 stringByAppendingPathComponent:FILE_TO_SAVE] atomically: YES];	
}

- (void)addStory:(UTHistoryStory *)story
{	
	if(story) {
		if(![self->m_stories containsObject:story]) {
			[self->m_stories addObject:story];
			[self saveStories];
			[[NSNotificationCenter defaultCenter] postNotificationName:UTHistoryManagerDidChangeNotification object:self userInfo:nil];
		}
	}
}

- (void)removeStory:(UTHistoryStory *)story
{	
	if(story) {
		if([self->m_stories containsObject:story]) {
			[self->m_stories removeObject:story];
			[self saveStories];
		}
	}
}


- (id)init
{
	self = [super init];
	
	if(self) {
		NSFileManager *fileManager = [NSFileManager defaultManager];
		
		if(![fileManager fileExistsAtPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:FILE_TO_SAVE]]) {
			NSMutableArray *temp = [NSMutableArray array];			
			NSData *plist = [NSPropertyListSerialization dataFromPropertyList:temp format:NSPropertyListXMLFormat_v1_0 errorDescription:nil];
			[fileManager createFileAtPath:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:FILE_TO_SAVE]
								 contents:plist attributes: nil];			
		}
		
		NSArray *storiesData = [[NSArray alloc] initWithContentsOfFile:[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:FILE_TO_SAVE]];

		self->m_stories = [[NSMutableArray alloc] init];
		for(NSString *id in storiesData) {
			UTHistoryStory *story = [[UTHistoryStory alloc] initWithId:id];
			[self->m_stories addObject:story];
			[story release];
		}
				
		[storiesData release];
	}
	return self;
}

#pragma mark NSObject

- (void)dealloc
{
	[self->m_stories release];
	[super dealloc];
}

@end
