//
//  UITableView+PullToRefresh.m
//

#import "UITableView+PullToRefresh.h"

static const int kTimeoutInSeconds = 30;
static BOOL pullToRefreshSymbolIsBright;


@implementation UITableView (PullToRefresh)

- (void)refreshFromControl:(UIRefreshControl *)sender {
	
	if ([self.dataSource respondsToSelector:@selector(refreshFromControl:)]) {
		[self.dataSource performSelector:@selector(refreshFromControl:) withObject:sender];
	}
	
	int timeoutIdentifier = (int)[NSDate timeIntervalSinceReferenceDate]%100000;
	sender.tag = timeoutIdentifier;
	
	int64_t timeoutInSeconds = kTimeoutInSeconds;
	dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, timeoutInSeconds * NSEC_PER_SEC);
	dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
		
		if (sender.tag != timeoutIdentifier)
			// A different timeout has started inbetween.
			return;
		
		if (sender.refreshing)
			[sender endRefreshing];
	});
	
}

- (void)setCanPullToRefresh:(BOOL)canPullToRefresh {
	if (canPullToRefresh) {
		
		UITableViewController *tableViewController = [[UITableViewController alloc] init];
		tableViewController.tableView = self;
		
		UIRefreshControl * refreshControl = [[UIRefreshControl alloc] init];
		[refreshControl addTarget:self action:@selector(refreshFromControl:)
				 forControlEvents:UIControlEventValueChanged];
		tableViewController.refreshControl = refreshControl;
	}
	else {
		if (self.canPullToRefresh) {
			for (UIView * subview in self.subviews) {
				if ([subview isKindOfClass:[UIRefreshControl class]]) {
					[subview removeFromSuperview];
				}
			}
		}
	}
}

- (BOOL)canPullToRefresh {
	for (UIView * subview in self.subviews) {
		if ([subview isKindOfClass:[UIRefreshControl class]]) {
			return YES;
		}
	}
	return NO;
}

- (void)setPullToRefreshSymbolIsBright:(BOOL)isBright {
	pullToRefreshSymbolIsBright = isBright;
}

@end
