//
//  NSFileHandle+YSRACSupport.m
//  ReactiveObjC
//
//  Created by Josh Abernathy on 5/10/12.
//  Copyright (c) 2012 GitHub. All rights reserved.
//

#import "NSFileHandle+YSRACSupport.h"
#import "NSNotificationCenter+YSRACSupport.h"
#import "NSObject+YSRACDescription.h"
#import "YSRACReplaySubject.h"
#import "YSRACDisposable.h"

@implementation NSFileHandle (YSRACSupport)

- (YSRACSignal *)ysrac_readInBackground {
	YSRACReplaySubject *subject = [YSRACReplaySubject subject];
	[subject setNameWithFormat:@"%@ -ysrac_readInBackground", YSRACDescription(self)];

	YSRACSignal *dataNotification = [[[NSNotificationCenter defaultCenter] ysrac_addObserverForName:NSFileHandleReadCompletionNotification object:self] map:^(NSNotification *note) {
		return note.userInfo[NSFileHandleNotificationDataItem];
	}];
	
	__block YSRACDisposable *subscription = [dataNotification subscribeNext:^(NSData *data) {
		if (data.length > 0) {
			[subject sendNext:data];
			[self readInBackgroundAndNotify];
		} else {
			[subject sendCompleted];
			[subscription dispose];
		}
	}];
	
	[self readInBackgroundAndNotify];
	
	return subject;
}

@end
