//
//  XTMutableAttributedStringHelper.m
//  XTads
//
//  Created by Rune Berg on 08/06/2019.
//  Copyright © 2019 Rune Berg. All rights reserved.
//

#import "XTMutableAttributedStringHelper.h"
#import "XTHtmlTagTab.h"
#import "XTCharConstants.h"


@implementation XTMutableAttributedStringHelper

static NSString * TAB_STOPS_KEY = @"XTads_tabStops";

+ (void)addTabTag:(XTHtmlTagTab *)tagTab toString:(NSMutableAttributedString *)attrString
{
	NSDictionary *attrsDict = [attrString attributesAtIndex:0 effectiveRange:nil];
	NSMutableDictionary *attrsDictMutable = [NSMutableDictionary dictionaryWithDictionary:attrsDict];
	NSMutableArray *tabStops = [attrsDictMutable objectForKey:TAB_STOPS_KEY];
	if (tabStops == nil) {
		tabStops = [NSMutableArray arrayWithCapacity:10];
		[attrsDictMutable setObject:tabStops forKey:TAB_STOPS_KEY];
	}
	[tabStops addObject:tagTab];
	
	NSRange range = NSMakeRange(0, attrString.length);
	[attrString setAttributes:attrsDictMutable range:range];
}

+ (NSArray<XTHtmlTagTab *> *)getTabTagsForString:(NSAttributedString *)attrString
{
	NSArray<XTHtmlTagTab *> *res;
	if (attrString == nil || attrString.length == 0) {
		res = nil;
	} else {
		//if char at idx 0 is zwsp, use idx 1 (if within string length)
		unichar ch0 = [attrString.string characterAtIndex:0];
		NSUInteger idx;
		if (ch0 == '\t') {
			idx = 0;
		} else {
			if (ch0 == ZERO_WIDTH_SPACE_CHAR && attrString.length >= 2) {
				unichar ch1 = [attrString.string characterAtIndex:1];
				if (ch1 == '\t') {
					idx = 1;
				} else {
					idx = 0;
				}
			} else {
				idx = 0;
			}
		}
		NSDictionary *attrsDict = [attrString attributesAtIndex:idx effectiveRange:nil];
		res = [attrsDict objectForKey:TAB_STOPS_KEY];
	}
	return res;
}

+ (void)removeTabTagsForString:(NSMutableAttributedString *)mutAttrString
{
	NSRange range = NSMakeRange(0, mutAttrString.length);
	[mutAttrString removeAttribute:TAB_STOPS_KEY range:range];
}

+ (BOOL)isFromExpandedTabTagWithIndent:(NSAttributedString *)attrString
{
	BOOL res = NO;
	NSArray<XTHtmlTagTab *> *tabTagArray = [XTMutableAttributedStringHelper getTabTagsForString:attrString];
	for (XTHtmlTagTab *tabTag in tabTagArray) {
		if ([tabTag hasAttribute:@"indent"]) {
			res = YES;
			break;
		}
	}
	return res;
}

+ (NSArray *)tagTabStopsForAttrAtring:(NSAttributedString *)attrString
{
	NSArray *res = [attrString attribute:TAB_STOPS_KEY atIndex:0 effectiveRange:0];
	return res;
}

+ (void)setTagTabStops:(NSArray *)tagTabStops forMutAttrAtring:(NSMutableAttributedString *)mutAttrString
{
	NSRange range = NSMakeRange(0, mutAttrString.length);
	[mutAttrString addAttribute:TAB_STOPS_KEY value:tagTabStops range:range];
}

@end
