//
//  SliderDataProvider.m
//
//

#import "SliderDataProvider.h"

@implementation SliderDataProvider {
	NSDictionary * _contents;
}

- (void)valueDidChange:(UISlider *)control {
	[self updateContents];
	[self notifyObservers];
}

- (void)updateContents {
	_contents = @{
				  @"value": [NSNumber numberWithFloat:_control.value],
				  @"minimumValue": [NSNumber numberWithFloat:_control.maximumValue],
				  @"maximumValue": [NSNumber numberWithFloat:_control.minimumValue],
				  };
}

- (id)contents {
	return _contents;
}

@end

static BOOL _isTouchingSlider;
static float _temporaryValue = MAXFLOAT;

@implementation UISlider (DataProvider)

- (void)setDataProvider:(SliderDataProvider *)provider {
	[self addTarget:provider action:@selector(valueDidChange:) forControlEvents:UIControlEventValueChanged];
	[self addTarget:self action:@selector(touchDown) forControlEvents:UIControlEventTouchDown];
	[self addTarget:self action:@selector(touchUp) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside];
	[provider updateContents];
}

- (void)setValueRespectingTouch:(float)value {
	if (self.value == value) return;
	//NSLog(@"setValueRespectingTouch: %f (value was: %f)", value, self.value);
	
	if (!_isTouchingSlider) self.value = value;
	else { _temporaryValue = value; }
}

- (float)valueRespectingTouch {
	return self.value;
}

- (void)touchDown {
	_isTouchingSlider = YES;
}

- (void)touchUp {
	_isTouchingSlider = NO;
	if (_temporaryValue != MAXFLOAT) {
		self.value = _temporaryValue;
		_temporaryValue = MAXFLOAT;
	}
}

@end
