#import "CSVDataSource.h"
#import "CSV2JSON.h"

@implementation CSVDataSource {
	NSArray * _items;
}

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

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

- (id)contents {
	return _items;
}

- (NSArray *)items {
	return _items;
}


- (void)load {

	if (self.URLString) {
		[self sendRequestForURLFromString:self.URLString
								completion:^(NSURLResponse * response, NSData * data, NSError * error) {
									if (error) return;
									[self parseCSV:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
								}];
	}
	else if (self.dataString) {
		[self parseCSV:self.dataString];
	}
	
}

- (void)reset {
	_items = nil;
}

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

- (void)parseCSV:(NSString *)csvString {

	_items = nil;

	if ([csvString isKindOfClass:[NSString class]] && csvString.length) {
		CSVParser * parser = [CSVParser.alloc init];
		parser.csvString = csvString;
		if ([parser parse]) {
			_items = [NSJSONSerialization JSONObjectWithData:parser.jsonData options:0 error:nil];
		}
	}
	
	[self notifyObservers];
	return;
}




#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 {
	return _items[indexPath.row];
}


@end
