//
//  SSCiflyTool.m
//  语音识别
//
//  Created by 吴雁江 on 18/1/6.
//  Copyright © 2018年. All rights reserved.
//

#import "SSCiflyTool.h"
#import "IATConfig.h"
#import "ISRDataHelper.h"
#import "IFLYDialogView.h"
#import <MBProgressHUD/MBProgressHUD.h>

@interface SSCiflyTool()<IFlySpeechRecognizerDelegate, IFLYDialogViewDelegate>

/**不带界面的识别对象**/
@property (nonatomic, strong) IFlySpeechRecognizer *speechRecognizer;

@property(nonatomic,copy)RecognizerBlock block;

@property (nonatomic, strong) IFLYDialogView *dialogView;

@end


@implementation SSCiflyTool
#pragma mark - getter & setter
- (IFLYDialogView *)dialogView {

    if (!_dialogView) {
        _dialogView = [[IFLYDialogView alloc] init];
    }
    return _dialogView;
}


- (IFlySpeechRecognizer *)speechRecognizer{
    
    if (!_speechRecognizer) {
        IFlySpeechRecognizer *speechRecognizer =[IFlySpeechRecognizer sharedInstance];
        speechRecognizer.delegate = self;
        [speechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        //设置听写模式
        [speechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        
        IATConfig *instance = [IATConfig sharedInstance];
        //设置最长录音时间
        [speechRecognizer setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
        //设置后端点
        [speechRecognizer setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
        //设置前端点
        [speechRecognizer setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
        //网络等待时间
        [speechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
        
        //设置采样率，推荐使用16K
        [speechRecognizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
        if ([instance.language isEqualToString:[IATConfig chinese]]) {
            //设置语言
            [speechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            //设置方言
            [speechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
        }else if ([instance.language isEqualToString:[IATConfig english]]) {
            //设置语言
            [speechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
        }
        //设置是否返回标点符号
        [speechRecognizer setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
        
        self.speechRecognizer = speechRecognizer;
    }
    return _speechRecognizer;
}

+ (instancetype)shareTool{
    static SSCiflyTool *_tool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _tool = [[self alloc] init];
    });
    return _tool;
}

/**
开始录音
 ****/
- (void)startRecognizer:(RecognizerBlock)block{
    self.block = block;
    [self.speechRecognizer startListening];
    self.dialogView.delegate = self;
    [self.dialogView showInView:self.master animated:YES volume:0];

//    [self performSelector:@selector(delayToStartSpeaking) withObject:self afterDelay:0.05];
}
-(void)delayToStartSpeaking{
    if ([self.speechRecognizer startListening]) {
        self.dialogView.delegate = self;
        [self.dialogView showInView:self.master animated:YES volume:0];
    }
}

#pragma mark - <IFlyRecognizerViewDelegate>
- (void)onVolumeChanged:(int)volume {
    NSLog(@"声音大小为= %d",volume);
    [self.dialogView setVolume:volume];
}

/**
 有界面，听写结果回调
 resultArray：听写结果
 isLast：表示最后一次
 ****/
- (void)onResults:(NSArray *)results isLast:(BOOL)isLast
{
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [results objectAtIndex:0];
    
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    
    NSString * resultFromJson =  [ISRDataHelper stringFromJson:result];
    NSLog(@"result---%@",resultFromJson);
    self.block(nil,resultFromJson);
    [self.dialogView setDetailText:resultFromJson];
}
/**
 听写结束回调（注：无论听写是否正确都会回调）
 error.errorCode =
 0     听写正确
 other 听写出错
 ****/
- (void) onError:(IFlySpeechError *) error{
    [self.dialogView hide:YES];
    if (error.errorCode!=0) {
        NSLog(@"识别成功%@,error",error.errorDesc);
        self.block(error,nil);
    }else {
        // 识别失败
       NSLog(@"识别失败%@,error",error.errorDesc);
    }
}
#pragma mark - <IFLYDialogViewDelegate>

- (void)ifly_dialogView:(IFLYDialogView *)dialogView askHidingWithCancel:(BOOL)cancel {
    
    if (cancel) {
        [self.speechRecognizer cancel];
        [self.dialogView hide:YES];
    }else {
        [self.speechRecognizer stopListening];
    }
}
@end
