






#import "XXGProtocolLabel.h"
#import "XXGUIDriver.h"
#import "UIImage+XXGImage.h"

@implementation XXGProtocolLabel

+ (XXGProtocolLabel *)xxpk_protocolLabel {
    return [self xxpk_protocolLabel:YES];
}

+ (XXGProtocolLabel *)xxpk_protocolLabel:(BOOL)isCheckBox {
    
    XXGProtocolLabel *label = [[XXGProtocolLabel alloc] init];
    label.numberOfLines = 0;
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = [UIColor lightGrayColor];
    label.font = [UIFont systemFontOfSize:12];
    label.userInteractionEnabled = YES; 

    NSAttributedString *imageAttrString = nil;
    if (isCheckBox) {
        
        NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
        UIImage *templateImage = [[UIImage xxpk_imageBundleOfName:XXGUIDriver.xxpk_data_ui.xxpk_img_check_box_off] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        attachment.image = templateImage; 
        
        attachment.bounds = CGRectMake(0, -5, 20, 20);
        imageAttrString = [NSAttributedString attributedStringWithAttachment:attachment];
    }

    
    NSString *text = XXGUIDriver.xxpk_string_ui.xxpk_protocl;
    NSMutableAttributedString *textAttrString = [[NSMutableAttributedString alloc] initWithString:text];
    
    
    NSRange clickableRange = [text rangeOfString:XXGUIDriver.xxpk_string_ui.xxpk_protoclon];
    if (clickableRange.location != NSNotFound) {
        [textAttrString addAttribute:NSForegroundColorAttributeName value:[XXGUIDriver xxpk_mainColor] range:clickableRange];
        [textAttrString addAttribute:NSUnderlineStyleAttributeName value:@(NSUnderlineStyleSingle) range:clickableRange];
    }

    
    NSMutableAttributedString *combinedAttrString = [[NSMutableAttributedString alloc] init];
    if (imageAttrString) {
        [combinedAttrString appendAttributedString:imageAttrString];
    }
    [combinedAttrString appendAttributedString:textAttrString];
    
    label.attributedText = combinedAttrString;
    
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:label action:@selector(xxpk_handleLabelTap:)];
    [label addGestureRecognizer:tapGesture];
    
    return label;
}

- (void)setXxpk_isChecked:(BOOL)xxpk_isChecked {
    _xxpk_isChecked = !xxpk_isChecked;
    [self xxpk_toggleCheckboxImageForLabel:self];
}

- (void)xxpk_handleLabelTap:(UITapGestureRecognizer *)tapGesture {
    XXGProtocolLabel *label = (XXGProtocolLabel *)tapGesture.view;
    if (!label.attributedText) return;
    
    
    NSTextStorage *textStorage = [[NSTextStorage alloc] initWithAttributedString:label.attributedText];
    NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init];
    NSTextContainer *textContainer = [[NSTextContainer alloc] initWithSize:label.bounds.size];
    
    textContainer.lineFragmentPadding = 0;
    textContainer.maximumNumberOfLines = label.numberOfLines;
    textContainer.lineBreakMode = label.lineBreakMode;
    
    [textStorage addLayoutManager:layoutManager];
    [layoutManager addTextContainer:textContainer];
    
    
    [layoutManager ensureLayoutForTextContainer:textContainer];
    
    
    CGPoint tapLocation = [tapGesture locationInView:label];
    CGRect usedRect = [layoutManager usedRectForTextContainer:textContainer];
    CGPoint textContainerOrigin = CGPointMake(
        (label.bounds.size.width - usedRect.size.width) / 2,   
        (label.bounds.size.height - usedRect.size.height) / 2  
    );
    
    
    CGPoint locationInTextContainer = CGPointMake(
        tapLocation.x - textContainerOrigin.x,
        tapLocation.y - textContainerOrigin.y
    );
    
    
    __block BOOL isImageTapped = NO;
    [label.attributedText enumerateAttribute:NSAttachmentAttributeName
                                    inRange:NSMakeRange(0, label.attributedText.length)
                                    options:0
                                 usingBlock:^(id value, NSRange range, BOOL *stop) {
        if ([value isKindOfClass:[NSTextAttachment class]]) {
            
            NSRange glyphRange;
            [layoutManager glyphRangeForCharacterRange:range actualCharacterRange:&glyphRange];
            
            
            CGRect glyphRect = [layoutManager boundingRectForGlyphRange:glyphRange
                                                      inTextContainer:textContainer];
            
            
            CGRect actualGlyphRect = CGRectOffset(glyphRect, textContainerOrigin.x, textContainerOrigin.y);
            
            
            if (CGRectContainsPoint(actualGlyphRect, tapLocation)) {
                isImageTapped = YES;
                *stop = YES;
            }
        }
    }];
    
    if (isImageTapped) {
        
        
        [self xxpk_toggleCheckboxImageForLabel:label];
        return;
    }
    
    
    NSUInteger characterIndex = [layoutManager characterIndexForPoint:locationInTextContainer
                                                    inTextContainer:textContainer
                           fractionOfDistanceBetweenInsertionPoints:NULL];
    
    NSString *fullText = label.attributedText.string;
    NSRange clickableRange = [fullText rangeOfString:XXGUIDriver.xxpk_string_ui.xxpk_protoclon];
    
    if (characterIndex != NSNotFound && NSLocationInRange(characterIndex, clickableRange)) {
        
        
        if (self.xxpk_handleProtocolTap) {
            self.xxpk_handleProtocolTap();
        }
    }
}


- (void)xxpk_toggleCheckboxImageForLabel:(XXGProtocolLabel *)label {
    NSMutableAttributedString *attributedText = [label.attributedText mutableCopy];
    __block BOOL hasChanged = NO;
    
    [attributedText enumerateAttribute:NSAttachmentAttributeName
                             inRange:NSMakeRange(0, attributedText.length)
                             options:0
                          usingBlock:^(NSTextAttachment *oldAttachment, NSRange range, BOOL *stop) {
        if (![oldAttachment isKindOfClass:[NSTextAttachment class]]) return;
        
        
        BOOL isChecked = !_xxpk_isChecked;
        
        
        NSTextAttachment *newAttachment = [[NSTextAttachment alloc] init];
        
        
        UIColor *targetColor = isChecked ? [XXGUIDriver xxpk_mainColor]: UIColor.lightGrayColor;
        UIImage *originalImage = [UIImage xxpk_imageBundleOfName:isChecked ? XXGUIDriver.xxpk_data_ui.xxpk_img_check_box_on :XXGUIDriver.xxpk_data_ui.xxpk_img_check_box_off];
        
        
        newAttachment.image = [[originalImage imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]
                                imageWithTintColor:targetColor];
        newAttachment.bounds = oldAttachment.bounds;
        
        
        [attributedText removeAttribute:NSAttachmentAttributeName range:range];
        [attributedText addAttribute:NSAttachmentAttributeName value:newAttachment range:range];
        
        _xxpk_isChecked = isChecked;
        hasChanged = YES;
        *stop = YES;
    }];
    
    if (hasChanged) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [UIView transitionWithView:label
                              duration:0.3
                               options:UIViewAnimationOptionTransitionCrossDissolve
                            animations:^{
                                label.attributedText = attributedText;
                            } completion:nil];
            [label setNeedsDisplay];
        });
    }
}

@end
