//
//  TableViewSelectionDataProvider.m
//
//

#import "TableViewSelectionDataProvider.h"

@implementation TableViewSelectionDataProvider 

// Notification from the table view when the selection changed
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[self notifyObserversForSelectionChange];
}

- (id)contents {
	return self;
}

- (void)notifyObserversForSelectionChange {
}

// Single

- (NSNumber *)selectedItemIndex {
	NSArray * indexPaths = self.tableView.indexPathsForSelectedRows;
	if (!indexPaths || !indexPaths.count) { return @-1; }
	
	NSIndexPath * firstIndexPath = (NSIndexPath *)indexPaths[0];
	return @(firstIndexPath.item);
}

- (void)setSelectedItemIndex:(NSNumber *)selectedItemIndex {
	if (selectedItemIndex.integerValue < 0 || [self numberOfSectionsInTableView:self.tableView] == 0) { return; }
	if([self tableView:self.tableView numberOfRowsInSection:0] > selectedItemIndex.integerValue) {
		[self.tableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:selectedItemIndex.integerValue inSection:0] animated:YES scrollPosition:UITableViewScrollPositionMiddle];
		[self notifyObserversForSelectionChange];
	}
}

// Multiple
/*
- (NSArray *)selectedItemIndices {
	NSArray * indexPaths = self.indexPathsForSelectedRows;
	if (!indexPaths || !indexPaths.count) { return nil; }
	
	NSMutableArray * indices = @[].mutableCopy;
	for (NSIndexPath * indexPath in indexPaths) {
		[indices addObject:[NSNumber numberWithInteger:indexPath.row]];
	}
	return indices;
}

- (void)setSelectedItemIndices:(NSArray *)selectedItemIndices {
	for (NSNumber * index in selectedItemIndices) {
		[self selectRowAtIndexPath:[NSIndexPath indexPathForItem:index.integerValue inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
	}
}
*/

@end

@implementation UITableView (TableViewSelectionDataProviderExtension)

- (NSNumber *)selectedItemIndex {
	if([self.delegate respondsToSelector:@selector(selectedItemIndex)]) {
		return [(TableViewSelectionDataProvider *)self.delegate selectedItemIndex];
	}
	return @(NSNotFound);
}

- (void)setSelectedItemIndex:(NSNumber *)selectedItemIndex {
	if([self.delegate respondsToSelector:@selector(setSelectedItemIndex:)]) {
		[(TableViewSelectionDataProvider *)self.delegate setSelectedItemIndex:selectedItemIndex];
	}
}

@end
