//
//  UIControl+YSRACSignalSupportPrivate.m
//  ReactiveObjC
//
//  Created by Uri Baghin on 06/08/2013.
//  Copyright (c) 2013 GitHub, Inc. All rights reserved.
//

#import "UIControl+YSRACSignalSupportPrivate.h"
#import "NSObject+YSRACDeallocating.h"
#import "NSObject+YSRACLifting.h"
#import "YSRACChannel.h"
#import "YSRACCompoundDisposable.h"
#import "YSRACDisposable.h"
#import "YSRACSignal+Operations.h"
#import "UIControl+YSRACSignalSupport.h"

@implementation UIControl (YSRACSignalSupportPrivate)

- (YSRACChannelTerminal *)ysrac_channelForControlEvents:(UIControlEvents)controlEvents key:(NSString *)key nilValue:(id)nilValue {
	NSCParameterAssert(key.length > 0);
	key = [key copy];
	YSRACChannel *channel = [[YSRACChannel alloc] init];

	[self.ysrac_deallocDisposable addDisposable:[YSRACDisposable disposableWithBlock:^{
		[channel.followingTerminal sendCompleted];
	}]];

	YSRACSignal *eventSignal = [[[self
		ysrac_signalForControlEvents:controlEvents]
		mapReplace:key]
		takeUntil:[[channel.followingTerminal
			ignoreValues]
			catchTo:YSRACSignal.empty]];
	[[self
		ysrac_liftSelector:@selector(valueForKey:) withSignals:eventSignal, nil]
		subscribe:channel.followingTerminal];

	YSRACSignal *valuesSignal = [channel.followingTerminal
		map:^(id value) {
			return value ?: nilValue;
		}];
	[self ysrac_liftSelector:@selector(setValue:forKey:) withSignals:valuesSignal, [YSRACSignal return:key], nil];

	return channel.leadingTerminal;
}

@end
