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

#import "XTTextRecolorationTemplate.h"
#import "XTOutputFormatter.h"
#import "XTOutputTextColorResult.h"
#import "XTLogger.h"


@interface XTTextRecolorationTemplate ()

@property NSTextStorage *textStorage;

@end


@implementation XTTextRecolorationTemplate

static XTLogger* logger;

+ (void)initialize
{
	logger = [XTLogger loggerForClass:[XTTextRecolorationTemplate class]];
}

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

- (void)recolorForAttribute:(NSString *)attrName callback:(void(^)(NSRange, XTOutputTextColorResult *, XTColorSource))callback;
{
	[self internalRecolorForAttribute:attrName callback:^(NSRange range, XTOutputTextColorResult *colorResult) {
		XTColorSource colorSource = (colorResult != nil ? colorResult.colorSource : XT_COLOR_SOURCE_UNSPECIFIED);
		callback(range, colorResult, colorSource);
	}];
}

- (void)recolorForAttribute4:(NSString *)attrName callback:(void(^)(NSRange range, id attrValue))callback
{
	[self internalRecolorForAttribute:attrName callback:^(NSRange range, id attrValue) {
		callback(range, attrValue);
	}];
}

- (void)internalRecolorForAttribute:(NSString *)attrName callback:(void(^)(NSRange, id))callback
{
	//XT_DEF_SELNAME;
	
	NSTextStorage *textStorage = self.textStorage;
	NSUInteger textStorageLength = [textStorage length];
	
	if (textStorageLength == 0) {
		return;
	}
	
	[textStorage beginEditing];

	//if ([attrName isEqualToString:XT_OUTPUT_FORMATTER_ATTR_RECOLORABLE_TEXT_BACKGROUND]) {
	//	int brkpt = 1;
	//}
	
	NSUInteger substringCount = 0;
	NSUInteger idx = 0;
	while (idx < textStorageLength) {
		NSRange range;
		NSRange searchRange = NSMakeRange(idx, textStorageLength - idx);
		id attrValue = [textStorage attribute:attrName atIndex:idx longestEffectiveRange:&range inRange:searchRange];
		if (attrValue != nil) {
			callback(range, attrValue);
		}
		
		idx = range.location + range.length;
		//XT_WARN_2(@"range.location=%lu range.length=%lu", range.location, range.length);
		
		substringCount += 1;
	}
	
	[textStorage endEditing];
	
	//XT_WARN_1(@"substringCount=%lu", substringCount);
}

@end
