//
//  PickerDataSource.m
//

#import "PickerViewDataSource.h"
#import "PickerViewDataProvider.h"

@implementation PickerViewDataSource {
	NSArray * _values;
	UIPickerView * _pickerView;
	NSInteger _selectedRow;
	NSDictionary * _contents;
}

- (void)setValuesString:(NSString *)valuesString {
	_values = [valuesString componentsSeparatedByString:@"\n"];
}

- (void)setValues:(NSArray *)values {
	_values = values;
	[_pickerView reloadAllComponents];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
	if (!_pickerView) {
		_pickerView = pickerView;
		double delayInSeconds = 0.0;
		dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
		dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
			[_pickerView selectRow:_selectedRow inComponent:0 animated:NO];
		});
	}
	return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
	return _values.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
	if (row < 0 || row > _values.count) return nil;
	return _values[row];
}

- (void)setSelectedRow:(NSUInteger)row {
	_selectedRow = row;
	if (_pickerView) [_pickerView selectRow:_selectedRow inComponent:0 animated:YES];
}

- (NSUInteger)selectedRow {
	return _selectedRow;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
	_selectedRow = row;
	[self.dataProvider updateContents];
	[self.dataProvider notifyObservers];
}

@end

@implementation UIPickerView (DataLinkExtensions)

- (void)setTitleStrings:(NSArray *)titleStrings {
	[(PickerViewDataSource *)self.dataSource setValues:titleStrings];
}

- (void)setSelectedRow1:(NSNumber *)selectedRow1 {
	[self selectRow:selectedRow1.integerValue-1 inComponent:0 animated:YES];
}

- (NSInteger)selectedRow1 {
	return [self selectedRowInComponent:0]+1;
}

- (void)setSelectedRow:(NSNumber *)selectedRow {
	[self selectRow:selectedRow.integerValue inComponent:0 animated:YES];
}

- (NSInteger)selectedRow {
	return [self selectedRowInComponent:0];
}

@end