#import "RSS2DataSource.h"
#import "RSS2Parser.h"


@implementation RSS2DataSource {
	NSDictionary * _contents;
	NSMutableArray * _items;
}


- (void)load {
	
	if (self.URLString) {
		[self sendRequestForURLFromString:self.URLString
								completion:^(NSURLResponse * response, NSData * data, NSError * error) {
									if (error) return;
									[self parseFeedAndDisplay:data];
								}];
	}
	else if (self.dataString) {
		[self parseFeedAndDisplay:[self.dataString dataUsingEncoding:NSUTF8StringEncoding]];
	}
	
}

- (void)setURLString:(NSString *)URLString {
	_URLString = [URLString copy];
	_dataString = nil;
	[self load];
}

- (void)setDataString:(NSString *)dataString {
	_dataString = [dataString copy];
	_URLString = nil;
	[self load];
}

- (void)parseFeed:(NSData *)feedData onSuccess:(void(^)(NSDictionary * feed))success {
	
	RSS2Parser * parser = RSS2Parser.new;
	parser.inputData = feedData;
	if (![parser parse]) {
		NSLog(@"Parsing failed.");
		return;
	}
	
	if (success) success(parser.channelDictionaryRepresentation);
}

- (void)parseFeedAndDisplay:(NSData *)feedData {
	[self parseFeed:feedData onSuccess:^(NSDictionary *feed) {
		_contents = feed;
		_items = _contents[@"item"];
		
		[self notifyObservers];
	}];
}

- (id)contents {
	return _contents;
}


- (BOOL)didLoad {
	return _contents != nil;
}


#pragma mark - DataSourceBase methods

- (NSInteger)numberOfSections {
	if (!self.didLoad) return 0;
	if (![_items isKindOfClass:[NSArray class]]) return 0;
	return 1;
}

- (NSInteger)numberOfItemsInSection:(NSInteger)section {
	return _items.count;
}

- (NSDictionary *)datasetForItemAtIndexPath:(NSIndexPath *)indexPath {
	if (indexPath.row >= _items.count) return nil;
	return _items[indexPath.row];
}

#pragma mark - Pagination

- (NSString *)nextLink {
	NSString * __block nextLink = nil;
	[((NSArray *)_contents[@"links"]) enumerateObjectsUsingBlock:^(NSDictionary * linkInfo, NSUInteger idx, BOOL *stop) {
		if ([[linkInfo objectForKey:@"rel"] isEqualToString:@"next"]) {
			nextLink = [linkInfo objectForKey:@"href"];
			*stop = YES;
		}
	}];
	return nextLink;
}

- (BOOL)canLoadMore {
	NSString * nextLink = [self nextLink];
	return nextLink.length;
}

- (void)loadMore {
	
	NSString * nextLink = [self nextLink];
	if (!nextLink.length) return;
		
	[self sendRequestForURLFromString:nextLink
							completion:^(NSURLResponse * response, NSData * data, NSError * error) {
								if (error) return;
								[self parseFeed:data onSuccess:^(NSDictionary *feed) {
									_contents = feed;
									_items = [NSMutableArray arrayWithArray:_items];
									[_items addObjectsFromArray:_contents[@"item"]];
									
									[self notifyObserversWithUpdate:YES];
								}];
							}];

}

@end
