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

#import "AAILoadView.h"
#import "UIColor+AAILD.h"

@interface AAILoadView ()

@property (nonatomic, strong) CAShapeLayer *greenLayer;

@end

@implementation AAILoadView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.accessibilityIdentifier = @"AAILoadView";
        
        _brandColor = [UIColor aaild_brandColor];
        _greenLayer = [CAShapeLayer layer];
        _greenLayer.strokeColor = _brandColor.CGColor;
        _greenLayer.lineWidth = 3;
        _greenLayer.fillColor = [UIColor clearColor].CGColor;
        _greenLayer.lineCap = kCALineCapRound;
        
        [self.layer addSublayer:_greenLayer];
        _greenLayer.frame = self.bounds;
    }
    return self;
}

- (void)setBrandColor:(UIColor *)brandColor
{
    _brandColor = brandColor;
    _greenLayer.strokeColor = brandColor.CGColor;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    self.greenLayer.frame = self.bounds;
    
    CGFloat width = self.bounds.size.width;
    UIBezierPath *greenPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(width / 2, width / 2)
                                                             radius:(width / 2) - (3 / 2)
                                                         startAngle:0
                                                           endAngle:(3.0 / 2.0) * M_PI
                                                          clockwise:YES];
    self.greenLayer.path = greenPath.CGPath;
}

- (void)startAnimation {
    if (self.isAnimating) {
        return;
    }
    self.hidden = NO;
    
    CATransform3D transform = CATransform3DMakeRotation(M_PI / 2, 0, 0, 1);
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform"];
    animation.duration = 0.25;
    animation.repeatCount = HUGE_VALF;
    animation.cumulative = YES;
    animation.removedOnCompletion = NO;
    animation.fromValue = [NSValue valueWithCATransform3D:CATransform3DIdentity];
    animation.toValue = [NSValue valueWithCATransform3D:transform];
    
    [self.layer addAnimation:animation forKey:@"transform"];
}

- (void)stopAnimation {
    self.hidden = YES;
    [self.layer removeAllAnimations];
}

- (BOOL)isAnimating {
    return [self.layer animationForKey:@"transform"] != nil;
}

@end

