//
//  YSRACSubscriptionScheduler.m
//  ReactiveObjC
//
//  Created by Josh Abernathy on 11/30/12.
//  Copyright (c) 2012 GitHub, Inc. All rights reserved.
//

#import "YSRACSubscriptionScheduler.h"
#import "YSRACScheduler+Private.h"

@interface YSRACSubscriptionScheduler ()

// A private background scheduler on which to subscribe if the +currentScheduler
// is unknown.
@property (nonatomic, strong, readonly) YSRACScheduler *backgroundScheduler;

@end

@implementation YSRACSubscriptionScheduler

#pragma mark Lifecycle

- (instancetype)init {
	self = [super initWithName:@"org.reactivecocoa.ReactiveObjC.YSRACScheduler.subscriptionScheduler"];

	_backgroundScheduler = [YSRACScheduler scheduler];

	return self;
}

#pragma mark YSRACScheduler

- (YSRACDisposable *)schedule:(void (^)(void))block {
	NSCParameterAssert(block != NULL);

	if (YSRACScheduler.currentScheduler == nil) return [self.backgroundScheduler schedule:block];

	block();
	return nil;
}

- (YSRACDisposable *)after:(NSDate *)date schedule:(void (^)(void))block {
	YSRACScheduler *scheduler = YSRACScheduler.currentScheduler ?: self.backgroundScheduler;
	return [scheduler after:date schedule:block];
}

- (YSRACDisposable *)after:(NSDate *)date repeatingEvery:(NSTimeInterval)interval withLeeway:(NSTimeInterval)leeway schedule:(void (^)(void))block {
	YSRACScheduler *scheduler = YSRACScheduler.currentScheduler ?: self.backgroundScheduler;
	return [scheduler after:date repeatingEvery:interval withLeeway:leeway schedule:block];
}

@end
