//
//  UIControl+YSRACSignalSupport.m
//  ReactiveObjC
//
//  Created by Josh Abernathy on 4/17/12.
//  Copyright (c) 2012 GitHub, Inc. All rights reserved.
//

#import "UIControl+YSRACSignalSupport.h"
#import "YSRACEXTScope.h"
#import "YSRACCompoundDisposable.h"
#import "YSRACDisposable.h"
#import "YSRACSignal.h"
#import "YSRACSubscriber.h"
#import "NSObject+YSRACDeallocating.h"
#import "NSObject+YSRACDescription.h"

@implementation UIControl (YSRACSignalSupport)

- (YSRACSignal *)ysrac_signalForControlEvents:(UIControlEvents)controlEvents {
	@weakify(self);

	return [[YSRACSignal
		createSignal:^(id<YSRACSubscriber> subscriber) {
			@strongify(self);

			[self addTarget:subscriber action:@selector(sendNext:) forControlEvents:controlEvents];

			YSRACDisposable *disposable = [YSRACDisposable disposableWithBlock:^{
				[subscriber sendCompleted];
			}];
			[self.ysrac_deallocDisposable addDisposable:disposable];

			return [YSRACDisposable disposableWithBlock:^{
				@strongify(self);
				[self.ysrac_deallocDisposable removeDisposable:disposable];
				[self removeTarget:subscriber action:@selector(sendNext:) forControlEvents:controlEvents];
			}];
		}]
		setNameWithFormat:@"%@ -ysrac_signalForControlEvents: %lx", YSRACDescription(self), (unsigned long)controlEvents];
}

@end
