//
//  UIActionSheet+YSRACSignalSupport.m
//  ReactiveObjC
//
//  Created by Dave Lee on 2013-06-22.
//  Copyright (c) 2013 GitHub, Inc. All rights reserved.
//

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

@implementation UIActionSheet (YSRACSignalSupport)

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

	return proxy;
}

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

	YSRACUseDelegateProxy(self);

	return signal;
}

@end
