//
//  SLMikeInputView.m
//  SLAiELTS
//
//  Created by Gusont on 2023/3/3.
//

#import "SLMikeInputView.h"
#import "SLMessageViewController.h"
@interface SLMikeInputView()

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *imgHeightConst;
@property (weak, nonatomic) IBOutlet UIImageView *mikeDhBg;

@end

@implementation SLMikeInputView

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self addContentView];
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self addContentView];
    }
    return self;
}

- (void)addContentView {
    [[NSBundle mainBundle] loadNibNamed:@"SLMikeInputView" owner:self options:nil];
    self.contentView.frame = self.bounds;
    [self addSubview:self.contentView];
    self.contentView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.8];
    UILongPressGestureRecognizer *gesture=[[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(handleLongPressGestures:)];
    gesture.minimumPressDuration= 0.3f;
    [self addGestureRecognizer:gesture];
//    gesture.numberOfTouchesRequired = 1;
    UIImage *img = self.mikeInputImageView.image;
    [img resizableImageWithCapInsets:UIEdgeInsetsMake(90, 0, 0, 0) resizingMode:UIImageResizingModeStretch];
    self.mikeInputImageView.image = img;
    CGFloat h = 110 + kSafeAreaBottom;
    self.imgHeightConst.constant = h;
    self.clipsToBounds = YES;
    self.contentView.hidden = YES;
    [self nuiSpeechRecognizer];
    
    WS(weakSelf);
//    self.mikeTipImageView.animationDuration = 3.0;
    //动画时间
    //循环次数
    self.mikeTipImageView.animationRepeatCount = 0;
    //启动动画
    [self.mikeTipImageView startAnimating];
    NSString *dataPath = [[NSBundle mainBundle]pathForResource:@"icon_yb_bg_01" ofType:@"jpg"];
    NSData *data = [NSData dataWithContentsOfFile:dataPath];
    self.mikeTipImageView.image = [self decodeGifImageByData:data];
    self.nuiSpeechRecognizer.onVolumeChangedBlock = ^(CGFloat volume) {


    };
}
//解压gif的data为图片数组
-(UIImage *)decodeGifImageByData:(NSData *)data {
    //获取data资源器，这个可以直接操作图片data
    CGImageSourceRef source = CGImageSourceCreateWithData((__bridge CFDataRef)data, nil);
    //获取图片数量 size_t 类似于无符号int
    size_t count = CGImageSourceGetCount(source);
    UIImage * animationImage;
    
    //如果只有一张则直接解压
    if (count <= 1) {
        animationImage = [[UIImage alloc]initWithData:data];
    }
    else {
        NSMutableArray * imageArray = [NSMutableArray arrayWithCapacity:count];
        NSTimeInterval duration = 0.0f;
        //遍历获取每一张图片
        for (size_t i = 0; i < count; i++) {
            //解析图片拿到图片画笔拿到图片画笔
            CGImageRef imageRef = CGImageSourceCreateImageAtIndex(source, i, NULL);
            duration += [self imageDurationAtIndex:i source:source];
            //scale:图片缩放因子 默认1  orientation:图片绘制方向 默认网上
            [imageArray addObject:[UIImage imageWithCGImage:imageRef scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp]];
            CGImageRelease(imageRef);
        }
        
        //如果没有抓取到图片播放时间，则按照0.1秒一张的方式来了播放
        if (!duration) {
            duration = (1.0f / 10.0f) * count;
        }
        animationImage = [UIImage animatedImageWithImages:imageArray duration:duration];
    }
    
    
    CFRelease(source);
    return animationImage;
}

//获取每一张图片的持续时间
-(float)imageDurationAtIndex:(NSUInteger)index source:(CGImageSourceRef)source {
    float imageDuration = 0.1f;
    //获取指定图像的属性信息 如宽、高、持续时间等都在里面 详情参考 CGImageProperties
    CFDictionaryRef cfImageProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil);
    if (!cfImageProperties) {
        return imageDuration;
    }
    NSDictionary * imageProperties = (__bridge NSDictionary *) cfImageProperties;
    //拿到gif图的属性信息 获取每一帧的时间
    NSDictionary * gifProperties = [imageProperties valueForKey:(NSString *)kCGImagePropertyGIFDictionary];
    NSNumber * delayTime = [gifProperties valueForKey:(NSString *)kCGImagePropertyGIFUnclampedDelayTime];
    if (delayTime != nil) {
        return delayTime.floatValue;
    }
    
    return imageDuration;
}


- (void)handleLongPressGestures:(UILongPressGestureRecognizer *)paramSender {
    CGPoint point = [paramSender locationInView:paramSender.view];
    UIBezierPath *inputViewPath = [UIBezierPath bezierPathWithRect:self.mikeInputImageView.frame];
    if (CGPathContainsPoint(inputViewPath.CGPath, NULL, point, NO)) {
        
    }else{
    }
    UIBezierPath *cancelViewPath = [UIBezierPath bezierPathWithRect:self.mikeCancelImageView.frame];
    BOOL isContainCancelPath = CGPathContainsPoint(cancelViewPath.CGPath, NULL, point, NO);
    if (isContainCancelPath) {
        self.mikeCancelImageView.image = ImageName(@"icon_mike_cancel_sel");
        self.mikeInputImageView.image = ImageName(@"icon_mike_input_bg_sel");
        self.mikeDhBg.image = ImageName(@"icon_mike_dh_bg_sel");
        self.mikeLabel.text = @"松开 取消";
        if (paramSender.state == UIGestureRecognizerStateEnded){
            self.contentView.hidden = YES;
            self.frame = self.oldRect;
        }
    }else{
        self.mikeLabel.text = @"松开 发送";
        self.mikeDhBg.image = ImageName(@"icon_mike_dh_bg");
        self.mikeInputImageView.image = ImageName(@"icon_mike_input_bg");
        self.mikeCancelImageView.image = ImageName(@"icon_mike_cancel_nor");
    }
    if (paramSender.state == UIGestureRecognizerStateBegan) {
        self.frame = CGRectMake(0, 0, kSCREEN_WIDTH, kSCREEN_HEIGHT);
        self.contentView.hidden = NO;
        NSLog(@"SLMikeInputView long pressTap state :begin");
        [self.nuiSpeechRecognizer startSpeechRecognizer];
        UIImpactFeedbackGenerator *generator = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleHeavy];
        [generator impactOccurred];
        SLMessageViewController *vc = (SLMessageViewController *)self.viewController;
        if ([vc isKindOfClass:SLMessageViewController.class]) {
            UIView *view = [vc.view viewWithTag:SLImHintLabelTag];
            view.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.5];
        }
    }else if (paramSender.state == UIGestureRecognizerStateChanged){

    }else if (paramSender.state == UIGestureRecognizerStateEnded){
        NSLog(@"SLMikeInputView long pressTap state :ended");
        self.contentView.hidden = YES;
        self.frame = self.oldRect;
        [self.nuiSpeechRecognizer stopSpeechRecognizer:!isContainCancelPath];
        SLMessageViewController *vc = (SLMessageViewController *)self.viewController;
        if ([vc isKindOfClass:SLMessageViewController.class]) {
            [UIView animateWithDuration:1 animations:^{
                UIView *view = [vc.view viewWithTag:SLImHintLabelTag];
                view.backgroundColor = [UIColor whiteColor];
            }];
        }
    }else {
        NSLog(@"SLMikeInputView long pressTap state :end");
        [self.nuiSpeechRecognizer stopSpeechRecognizer:NO];
    }
}

- (SLNuiSpeechRecognizer *)nuiSpeechRecognizer {
    if (!_nuiSpeechRecognizer) {
        _nuiSpeechRecognizer = [[SLNuiSpeechRecognizer alloc] init];
    }
    return _nuiSpeechRecognizer;
}

- (void)alertShow {
    UIWindow* window = nil;
    if (@available(iOS 13.0, *)) {
        for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes)
        {
            if (windowScene.activationState == UISceneActivationStateForegroundActive)
            {
                window = windowScene.windows.firstObject;
                break;
            }
        }
    }else {
        window = [[UIApplication sharedApplication].delegate window];
    }
    [window makeKeyAndVisible];
    [window makeKeyWindow];
    [window addSubview:self];
}

@end
