//
//  XTTextStorageParagraphTemplate.m
//  XTads
//
//  Created by Rune Berg on 29/05/2020.
//  Copyright © 2020 Rune Berg. All rights reserved.
//

#import "XTTextStorageParagraphTemplate.h"
#import "XTStringUtils.h"


@interface XTTextStorageParagraphTemplate ()

@property (weak) NSTextStorage *textStorage;

@end


@implementation XTTextStorageParagraphTemplate

+ (instancetype)forTextStorage:(NSTextStorage *)textStorage
{
	XTTextStorageParagraphTemplate *instance = [XTTextStorageParagraphTemplate new];
	instance.textStorage = textStorage;
	return instance;
}

- (void)doForEachParagraphInRange:(NSRange)range excludeNewlines:(BOOL)excludeNewlines callback:(void(^)(NSRange))callback
{
	if (range.length == 0) {
		return;
	}
	
	NSString *string = self.textStorage.string;
	NSUInteger idx = range.location;
	NSUInteger idxPastEnd = range.location + range.length;

	while (idx < idxPastEnd) {
		NSRange paraRange = [XTStringUtils rangeOfNextParagraphIn:string fromLoc:idx];
		if (paraRange.location != NSNotFound) {
			NSRange paraRangeUsed = NSMakeRange(paraRange.location, paraRange.length);
			if (excludeNewlines) {
				NSUInteger idxLastCharInPara = paraRange.location + paraRange.length - 1;
				unichar lastCharInPara = [string characterAtIndex:idxLastCharInPara];
				if (lastCharInPara == '\n') {
					paraRangeUsed.length -= 1;
				}
			}
			if (paraRangeUsed.length >= 1) {
				callback(paraRangeUsed);
			}
			idx += paraRange.length;
		}
	}
}
	
@end
