//
//  UIAlertView+YSRACSignalSupport.m
//  ReactiveObjC
//
//  Created by Henrik Hodne on 6/16/13.
//  Copyright (c) 2013 GitHub, Inc. All rights reserved.
//

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

@implementation UIAlertView (YSRACSignalSupport)

static void YSRACUseDelegateProxy(UIAlertView *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(UIAlertViewDelegate)];
		objc_setAssociatedObject(self, _cmd, proxy, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
	}

	return proxy;
}

- (YSRACSignal *)ysrac_buttonClickedSignal {
	YSRACSignal *signal = [[[[self.ysrac_delegateProxy
		signalForSelector:@selector(alertView:clickedButtonAtIndex:)]
		reduceEach:^(UIAlertView *alertView, NSNumber *buttonIndex) {
			return buttonIndex;
		}]
		takeUntil:self.ysrac_willDeallocSignal]
		setNameWithFormat:@"%@ -ysrac_buttonClickedSignal", YSRACDescription(self)];

	YSRACUseDelegateProxy(self);

	return signal;
}

- (YSRACSignal *)ysrac_willDismissSignal {
	YSRACSignal *signal = [[[[self.ysrac_delegateProxy
		signalForSelector:@selector(alertView:willDismissWithButtonIndex:)]
		reduceEach:^(UIAlertView *alertView, NSNumber *buttonIndex) {
			return buttonIndex;
		}]
		takeUntil:self.ysrac_willDeallocSignal]
		setNameWithFormat:@"%@ -ysrac_willDismissSignal", YSRACDescription(self)];

	YSRACUseDelegateProxy(self);

	return signal;
}

@end
