//
//  AAILoadingHud.m
//  AAILivenessUI
//
//  Created by loong on 2024/7/10.
//

#import "AAILoadingHud.h"
#import "AAILoadView.h"
#import "UIView+AAILD.h"

@interface AAILoadingHud ()
{
    UILabel * _titleLabel;
}
@end

@implementation AAILoadingHud

- (instancetype)initWithText:(NSString *)text
                  brandColor:(UIColor *)brandColor {
    return [self initWithText:text brandColor:brandColor font:nil];
}

- (instancetype)initWithText:(NSString *)text
                  brandColor:(UIColor *)brandColor
                        font:(UIFont * _Nullable)font {
    self = [super initWithFrame:CGRectZero];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.accessibilityIdentifier = NSStringFromClass(self.class);
        
        UIStackView *colum = [[UIStackView alloc] init];
        colum.axis = UILayoutConstraintAxisVertical;
        colum.alignment = UIStackViewAlignmentCenter;
        colum.spacing = 24;
        colum.translatesAutoresizingMaskIntoConstraints = NO;
        AAILoadView *loadingView = [[AAILoadView alloc] init];
        loadingView.brandColor = brandColor;
        [loadingView aaild_width:@56 height:@56];

        UILabel *label = [[UILabel alloc] init];
        label.text = text;
        label.numberOfLines = 0;
        label.textAlignment = NSTextAlignmentCenter;
        if (font) {
            label.font = font;
        } else {
            label.font = [UIFont boldSystemFontOfSize:16];
        }
        label.translatesAutoresizingMaskIntoConstraints = NO;
        [colum addArrangedSubview:loadingView];
        [colum addArrangedSubview:label];

        [self addSubview:colum];
        
        [colum aaild_marginToView:self t:@(74 + 64) l:@0 b:nil r:@0];
        // The constraint connecting the label's width to the stack view's width
        // must be activated after the stack view's own width-defining constraints are active.
        [label.widthAnchor constraintEqualToAnchor:colum.widthAnchor].active = YES;
        _titleLabel = label;
        
        [loadingView startAnimation];
    }
    return self;
}

- (void)showInView:(UIView *)view {
    self.tag = 1379;
    [view addSubview:self];

    [self aaild_marginToView:view t:@0 l:@0 b:@0 r:@0];
}

+ (void)dismissInView:(UIView *)view {
    UIView *hud = [view viewWithTag:1379];
    if (hud) {
        [hud removeFromSuperview];
    }
}

- (void)updateTitleLabelAccId:(NSString *)accessibilityIdentifier
{
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self updateTitleLabelAccId:accessibilityIdentifier];
        });
        return;
    }

    _titleLabel.accessibilityIdentifier = accessibilityIdentifier;
    _titleLabel.accessibilityLabel = accessibilityIdentifier;
    _titleLabel.isAccessibilityElement = YES;
    self.accessibilityValue = accessibilityIdentifier;
    UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, _titleLabel);
}

@end

