//
//  UIImagePickerController+YSRACSignalSupport.m
//  ReactiveObjC
//
//  Created by Timur Kuchkarov on 28.03.14.
//  Copyright (c) 2014 GitHub. All rights reserved.
//

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

@implementation UIImagePickerController (YSRACSignalSupport)

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

- (YSRACSignal *)ysrac_imageSelectedSignal {
	YSRACSignal *pickerCancelledSignal = [[self.ysrac_delegateProxy
		signalForSelector:@selector(imagePickerControllerDidCancel:)]
		merge:self.ysrac_willDeallocSignal];
		
	YSRACSignal *imagePickerSignal = [[[[self.ysrac_delegateProxy
		signalForSelector:@selector(imagePickerController:didFinishPickingMediaWithInfo:)]
		reduceEach:^(UIImagePickerController *pickerController, NSDictionary *userInfo) {
			return userInfo;
		}]
		takeUntil:pickerCancelledSignal]
		setNameWithFormat:@"%@ -ysrac_imageSelectedSignal", YSRACDescription(self)];
    
	YSRACUseDelegateProxy(self);
    
	return imagePickerSignal;
}

@end
