//
//  UITextView+YSRACSignalSupport.m
//  ReactiveObjC
//
//  Created by Cody Krieger on 5/18/12.
//  Copyright (c) 2012 Cody Krieger. All rights reserved.
//

#import "UITextView+YSRACSignalSupport.h"
#import "YSRACEXTScope.h"
#import "NSObject+YSRACDeallocating.h"
#import "NSObject+YSRACDescription.h"
#import "YSRACDelegateProxy.h"
#import "YSRACSignal+Operations.h"
#import "YSRACTuple.h"
#import <objc/runtime.h>

@implementation UITextView (YSRACSignalSupport)

static void YSRACUseDelegateProxy(UITextView *self) {
    if (self.delegate == self.ysrac_delegateProxy) return;

    self.ysrac_delegateProxy.ysrac_proxiedDelegate = self.delegate;
    self.delegate = (id)self.ysrac_delegateProxy;
}

- (YSRACDelegateProxy *)ysrac_delegateProxy {
	YSRACDelegateProxy *proxy = objc_getAssociatedObject(self, _cmd);
	if (proxy == nil) {
		proxy = [[YSRACDelegateProxy alloc] initWithProtocol:@protocol(UITextViewDelegate)];
		objc_setAssociatedObject(self, _cmd, proxy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
	}

	return proxy;
}

- (YSRACSignal *)ysrac_textSignal {
	@weakify(self);
	YSRACSignal *signal = [[[[[YSRACSignal
		defer:^{
			@strongify(self);
			return [YSRACSignal return:YSRACTuplePack(self)];
		}]
		concat:[self.ysrac_delegateProxy signalForSelector:@selector(textViewDidChange:)]]
		reduceEach:^(UITextView *x) {
			return x.text;
		}]
		takeUntil:self.ysrac_willDeallocSignal]
		setNameWithFormat:@"%@ -ysrac_textSignal", YSRACDescription(self)];

	YSRACUseDelegateProxy(self);

	return signal;
}

@end
