//
//  UIButton+YSRACCommandSupport.m
//  ReactiveObjC
//
//  Created by Ash Furrow on 2013-06-06.
//  Copyright (c) 2013 GitHub, Inc. All rights reserved.
//

#import "UIButton+YSRACCommandSupport.h"
#import "YSRACEXTKeyPathCoding.h"
#import "YSRACCommand.h"
#import "YSRACDisposable.h"
#import "YSRACSignal+Operations.h"
#import <objc/runtime.h>

static void *UIButtonYSRACCommandKey = &UIButtonYSRACCommandKey;
static void *UIButtonEnabledDisposableKey = &UIButtonEnabledDisposableKey;

@implementation UIButton (YSRACCommandSupport)

- (YSRACCommand *)ysrac_command {
	return objc_getAssociatedObject(self, UIButtonYSRACCommandKey);
}

- (void)setRac_command:(YSRACCommand *)command {
	objc_setAssociatedObject(self, UIButtonYSRACCommandKey, command, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
	
	// Check for stored signal in order to remove it and add a new one
	YSRACDisposable *disposable = objc_getAssociatedObject(self, UIButtonEnabledDisposableKey);
	[disposable dispose];
	
	if (command == nil) return;
	
	disposable = [command.enabled setKeyPath:@keypath(self.enabled) onObject:self];
	objc_setAssociatedObject(self, UIButtonEnabledDisposableKey, disposable, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
	
	[self ysrac_hijackActionAndTargetIfNeeded];
}

- (void)ysrac_hijackActionAndTargetIfNeeded {
	SEL hijackSelector = @selector(ysrac_commandPerformAction:);
	
	for (NSString *selector in [self actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
		if (hijackSelector == NSSelectorFromString(selector)) {
			return;
		}
	}
	
	[self addTarget:self action:hijackSelector forControlEvents:UIControlEventTouchUpInside];
}

- (void)ysrac_commandPerformAction:(id)sender {
	[self.ysrac_command execute:sender];
}

@end
