//
//  NSMutableAttributedString+DDCategory.m
//  DDCategoryKit_Private
//  Created by DDIsFriend on 2022/7/29.

#import "NSMutableAttributedString+DDCategory.h"
#import "NSAttributedString+DDCategory.h"

@implementation NSMutableAttributedString (DDCategory)

- (NSMutableAttributedString *)dd_appendString:(NSString *)string attributes:(nullable NSDictionary<NSAttributedStringKey, id> *)attrs{
    // while self is not init yet, return string
    if (self.length == 0) {
        return [[NSMutableAttributedString alloc] initWithString:string attributes:attrs];
    }
    [self appendAttributedString:[[NSMutableAttributedString alloc] dd_initWithString:string attributes:attrs]];
    return self;
}

- (NSMutableAttributedString *)dd_appendAttributedString:(NSAttributedString *)attributedString{
    [self appendAttributedString:attributedString];
    return self;
}

- (NSAttributedString *)dd_immutable{
    return [[NSAttributedString alloc] initWithAttributedString:self];
}

- (NSMutableAttributedString *)dd_matchesRegularExpressionWithPattern:(NSString *)pattern withAttributes:(NSDictionary<NSAttributedStringKey,id> *)attrs{
    if (attrs == nil || [attrs isEqualToDictionary:@{}]) {
        return self;
    }
    NSError *error;
    NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    
    __weak typeof(self) weakSelf = self;
    [expression enumerateMatchesInString:self.string options:NSMatchingReportProgress range:NSMakeRange(0, self.string.length) usingBlock:^(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL * _Nonnull stop) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        
        [attrs enumerateKeysAndObjectsUsingBlock:^(NSAttributedStringKey  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            [strongSelf addAttribute:key value:obj range:[result range]];
        }];
       
    }];
    
    return self;
}

- (NSMutableAttributedString *)dd_firstMatchesRegularExpressionWithPattern:(NSString *)pattern withAttributes:(NSDictionary<NSAttributedStringKey,id> *)attrs{
    if (attrs == nil || [attrs isEqualToDictionary:@{}]) {
        return self;
    }
    NSError *error;
    NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
    
    NSRange range = [expression rangeOfFirstMatchInString:self.string options:NSMatchingReportProgress range:NSMakeRange(0, self.string.length)];
    
    __weak typeof(self) weakSelf = self;
    [attrs enumerateKeysAndObjectsUsingBlock:^(NSAttributedStringKey  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf addAttribute:key value:obj range:range];
    }];
    
    return self;
}
@end
