
#import "appdooPublisherDataSource.h"

NSMutableSet * allInstances;

@implementation appdooPublisherDataSource {
	NSMutableArray * _readEntriesStore;
	NSString * _dataType;
	NSArray * _groupItemResourceIDs;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        if (!allInstances) allInstances = [NSMutableSet set];
		[allInstances addObject:self];
    }
    return self;
}

- (void)setPublisherResourceID:(NSString *)publisherResourceID {
	_publisherResourceID = publisherResourceID;
	self.URLString = [NSString stringWithFormat:@"https://www.appdoo.info/publisher/api/1/resource/%@", publisherResourceID];
}

- (void)dealloc {
	[allInstances removeObject:self];
}

+ (void)updateInstancesWithResourceGroupID:(NSString *)resourceGroupID; {
	for (appdooPublisherDataSource * dataSource in allInstances) {
		if ([dataSource.publisherResourceID isEqualToString:resourceGroupID]) {
			[dataSource refresh];
			break;
		}
	}
}

- (void)markEntryRead:(NSDictionary *)entry {
	[self setEntry:entry isRead:YES];
}


- (BOOL)entryIsRead:(NSDictionary *)entry {
	[self setUpEntriesStore];
	NSString * identifier = [self identifierForEntry:entry];
	if (!identifier) return NO;
	return [_readEntriesStore containsObject:identifier];
}

- (void)setEntry:(NSDictionary *)entry isRead:(BOOL)isRead {
	[self setEntry:(NSDictionary *)entry isRead:(BOOL)isRead saveStoreAndNotify:YES];
}

- (void)setEntry:(NSDictionary *)entry isRead:(BOOL)isRead saveStoreAndNotify:(BOOL)notSilent {
	[self setUpEntriesStore];
	NSString * identifier = [self identifierForEntry:entry];
	if (!identifier) return;
	if ([_readEntriesStore containsObject:identifier]) return;
	[_readEntriesStore addObject:identifier];
	if (notSilent) {
		[self saveEntriesStore];
		[self notifyObserversWithUpdate:YES];
	}
}

- (NSString *)identifierForEntry:(NSDictionary *)entry {
	if (!self.isGroup) return nil;
	NSInteger index = [self.contents indexOfObject:entry];
	if (index == NSNotFound) return nil;
	NSString * identifier = nil;
	@try {
		identifier = _groupItemResourceIDs[index];
	}
	@catch (NSException *exception) {}
	return identifier;
}


- (void)setUpEntriesStore {
	if (_readEntriesStore) return;
	_readEntriesStore = [NSMutableArray arrayWithContentsOfFile:self.pathForEntriesStore];
	if (!_readEntriesStore) _readEntriesStore = @[].mutableCopy;
}

- (void)saveEntriesStore {
	//BOOL success =
	[_readEntriesStore writeToFile:self.pathForEntriesStore atomically:NO];
	
}

- (NSString *)pathForEntriesStore {
	NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString * documentsDirectory = [paths objectAtIndex:0];
	NSString * storePath = [[documentsDirectory stringByAppendingPathComponent:self.identifier] stringByAppendingPathExtension:@"plist"];
	return storePath;
}

- (void)markAllEntriesUnread {
	_readEntriesStore = @[].mutableCopy;
	[self saveEntriesStore];
	[self notifyObserversWithUpdate:YES];
}

- (void)markAllEntriesRead {
	for (NSDictionary * entry in self.contents) {
		[self setEntry:entry isRead:YES saveStoreAndNotify:NO];
	}
	[self saveEntriesStore];
	[self notifyObserversWithUpdate:YES];
}

- (void)parseJSON:(NSData *)jsonData {
	
	NSError * error = nil;
	
	NSJSONReadingOptions options = 0;
	options |= NSJSONReadingMutableContainers;
	id contents = [NSJSONSerialization JSONObjectWithData:jsonData options:options error:&error];
	
	if (error) {
		NSLog(@"Error parsing JSON: %@", error);
		NSString * jsonString = [NSString.alloc initWithData:jsonData encoding:NSUTF8StringEncoding];
		NSLog(@"The JSON string was: %@", jsonString);
		return;
	}
	
	if (self.isGroup || [[contents valueForKey:@"datasetType"] isEqualToString:@"group"]) {
		if ([contents isKindOfClass:[NSDictionary class]]) {
			_contents = [contents objectForKey:@"contents"];
			_groupItemResourceIDs = [contents objectForKey:@"ids"];
			self.isGroup = YES;
		}
	}
	else {
		_contents = contents;
	}
	
	[self notifyObservers];
	
}


- (NSDictionary *)datasetForItemAtIndexPath:(NSIndexPath *)indexPath {
	NSMutableDictionary * dataset = _contents[indexPath.row];
	if (![dataset isKindOfClass:[NSDictionary class]]) return @{};
	dataset[@"$appdoo$isRead"] = [self entryIsRead:dataset] ? @YES:@NO;
	dataset[@"$appdoo$originalDataSourceRef"] = self;
	return dataset;
}

@end

