//  PullToRefresh.mm

#import "PullToRefresh.h"
#import <objc/runtime.h>

static char kRefreshControlKey;
static char kRefreshActionKey;

@implementation UIScrollView (PullToRefresh)

- (UIRefreshControl *)addPullToRefresh:(PullToRefreshAction)action {
    UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];

    objc_setAssociatedObject(self,
                             &kRefreshActionKey,
                             action,
                             OBJC_ASSOCIATION_COPY_NONATOMIC);

    [refreshControl addTarget:self
                       action:@selector(handlePullToRefresh:)
             forControlEvents:UIControlEventValueChanged];

    self.refreshControl = refreshControl;
    objc_setAssociatedObject(self,
                             &kRefreshControlKey,
                             refreshControl,
                             OBJC_ASSOCIATION_RETAIN_NONATOMIC);

    return refreshControl;
}

- (void)handlePullToRefresh:(UIRefreshControl *)sender {
    PullToRefreshAction action =
        objc_getAssociatedObject(self, &kRefreshActionKey);

    if (action) {
        action(sender);
    }
}

- (void)endPullToRefresh {
    UIRefreshControl *refreshControl =
        objc_getAssociatedObject(self, &kRefreshControlKey);

    if (refreshControl.isRefreshing) {
        [refreshControl endRefreshing];
    }
}

@end
