//
//  TextualListDataSource.m
//

#import "TextualListDataSource.h"
#import "NSStringPunycodeAdditions.h"

@implementation TextualListDataSource {
	id _contents;
}

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

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

- (void)load {
	
	if (self.URLString) {
		[[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithUnicodeString:self.URLString]
									 completionHandler:^(NSData *data,
														 NSURLResponse *response,
														 NSError *error) {
										 if (error) {
											 NSLog(@"Connection Error: %@", error);
											 return;
										 }
										 if (!data) return;
										 
										 [self parseString:[NSString.alloc initWithData:data encoding:NSUTF8StringEncoding]];
									 }] resume];
	}
	else if (self.dataString) {
		[self parseString:self.dataString];
	}
	
}

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

- (id)contents {
	return _contents;
}

- (void)parseString:(NSString *)string {
	
	_contents = [string componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
	[self notifyObservers];
	
}


- (void)clear {
	_contents = nil;
}


- (void)reset {
	[self clear];
	[self notifyObservers];
}


- (NSInteger)numberOfSections {
	if (!_contents) return 0;
	if (![_contents isKindOfClass:[NSArray class]]) return 0;
	return 1;
}

- (NSInteger)numberOfItemsInSection:(NSInteger)section {
	if ([_contents isKindOfClass:[NSArray class]]) {
		return ((NSArray *)_contents).count;
	}
	return 0;
}

- (NSDictionary *)datasetForItemAtIndexPath:(NSIndexPath *)indexPath {
	return _contents[indexPath.row];
}

- (NSString *)description {
	if (_contents) return [NSString stringWithFormat:@"%@ { contents: %@ }", super.description, [_contents description]];
	return [NSString stringWithFormat:@"%@ { URL: %@, didLoad: %@ }", super.description, self.URLString, self.didLoad ? @"YES" : @"NO"];
	
}

@end
