#import "CPSUITableView.h"

@implementation CPSUITableView

// Delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[self deselectRowAtIndexPath:indexPath animated:YES];
	[self notifyObserversForSelectionChange];
	[self setAlwaysBounceVertical:YES];
}

- (void)awakeFromNib {
	[super awakeFromNib];
	self.delegate = self;
#ifdef IS_PREVIEW_APP
	if([self.dataSource isKindOfClass:NSClassFromString(@"StaticCellsDataSource")]) {
        CPSUITableView <UITableViewDelegate> *del = (CPSUITableView <UITableViewDelegate> *) self.dataSource;
		self.delegate = del;
	}
#endif
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	if(self.staticCellHeights != nil && self.staticCellHeights.length > 0) {
		NSArray *heights = [self.staticCellHeights componentsSeparatedByString:@","];
		if(indexPath.section == 0 && [heights count] > indexPath.row) {
			return [heights[indexPath.row] floatValue];
		}
	}
	return tableView.rowHeight;
}

// Single selection

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

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


// Multiple selection

- (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 {
	if([self.dataSource numberOfSectionsInTableView:self] == 0) { return; }
	for (NSNumber * index in selectedItemIndices) {
		if (index.integerValue >= 0 && [self numberOfRowsInSection:0] > index.integerValue) {
			[self selectRowAtIndexPath:[NSIndexPath indexPathForItem:index.integerValue inSection:0] animated:NO scrollPosition:UITableViewScrollPositionNone];
		}
	}
}


// State observing

- (CPSObservable *)observable {
	if (_observable == nil) { _observable = [[CPSObservable alloc] initWithObject:self]; }
	return _observable;
}

- (void)notifyObserversForSelectionChange {
	[self.observable notifyObserversForKeyPath:@"selectedItemIndex"];
	[self.observable notifyObserversForKeyPath:@"selectedItemIndices"];
}

@end
