//
//  UIBarButtonItem+YSRACCommandSupport.m
//  ReactiveObjC
//
//  Created by Kyle LeNeau on 3/27/13.
//  Copyright (c) 2013 GitHub, Inc. All rights reserved.
//

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

static void *UIControlYSRACCommandKey = &UIControlYSRACCommandKey;
static void *UIControlEnabledDisposableKey = &UIControlEnabledDisposableKey;

@implementation UIBarButtonItem (YSRACCommandSupport)

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

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

- (void)ysrac_hijackActionAndTargetIfNeeded {
	SEL hijackSelector = @selector(ysrac_commandPerformAction:);
	if (self.target == self && self.action == hijackSelector) return;
	
	if (self.target != nil) NSLog(@"WARNING: UIBarButtonItem.ysrac_command hijacks the control's existing target and action.");
	
	self.target = self;
	self.action = hijackSelector;
}

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

@end
