//
//  PickerViewDataProvider.m
//
//

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

@implementation PickerViewDataProvider {
	NSDictionary * _contents;
}

- (void)updateContents {
	NSString * text = @"";
	NSUInteger selectedRow = [(PickerViewDataSource *)_picker.dataSource selectedRow];
	if ([_picker.dataSource pickerView:_picker numberOfRowsInComponent:0] > selectedRow)
		text = [_picker.delegate pickerView:_picker titleForRow:selectedRow forComponent:0];
	_contents = @{
				  @"selectedRow": [NSNumber numberWithInteger:selectedRow],
				  @"selectedRow1": [NSNumber numberWithInteger:selectedRow+1],
				  @"selectedRowText": text
				  };
}

- (id)contents {
	return _contents;
}

- (void)setPicker:(UIPickerView *)picker {
	_picker = picker;
	[[NSOperationQueue mainQueue] addOperationWithBlock:^{
		[(id)_picker.dataSource setValue:self forKey:@"dataProvider"];
		[self updateContents];
		[self notifyObservers];
	}];
}

- (BOOL)didLoad {
	return (_contents && [[_contents objectForKey:@"selectedRowText"] length]);
}

@end

@implementation UIPickerView (DataProvider)

- (void)setDataProvider:(PickerViewDataProvider *)provider {
	provider.picker = self;
	[(id)self.dataSource setValue:provider forKey:@"dataProvider"];
	[provider updateContents];
}

@end
