//
//  IFLYSpeechTwo.m
//  MobilePortal
//
//  Created by caiyang on 2020/5/8.
//  Copyright © 2020 yin chen. All rights reserved.
//

#import "IFLYSpeechTwo.h"
#import "IFlyMSC/IFlyMSC.h"
#import "IATConfig.h"
#import "ISRDataHelper.h"


@interface IFLYSpeechTwo ()<IFlySpeechRecognizerDelegate,UIAlertViewDelegate>
//语义理解对象
@property (nonatomic, strong)IFlySpeechRecognizer *iFlySpeechRecognizer;
@property(strong,nonatomic)NSDictionary *dic;
@property (nonatomic, strong) NSString * result;
@property (nonatomic, strong) NSString * textViewText;
@end

@implementation IFLYSpeechTwo
+ (IFLYSpeechTwo *)ShareIFLYSpeechTwo{
    static IFLYSpeechTwo *iFLYSpeechTwo = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        iFLYSpeechTwo = [[IFLYSpeechTwo alloc]init];
    });
    return iFLYSpeechTwo;
}
-(void)initIfly{
    //Set log level
    [IFlySetting setLogFile:LVL_ALL];
    
    //Set whether to output log messages in Xcode console
    [IFlySetting showLogcat:YES];
    
    //Set the local storage path of SDK
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [paths objectAtIndex:0];
    [IFlySetting setLogFilePath:cachePath];
    NSString *initString = [[NSString alloc] initWithFormat:@"appid=%@", APPID_VALUE];
    [IFlySpeechUtility createUtility:initString];
}
/// 开始
-(void)startParsing{
    //检查权限
    [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
        
        if (granted) {//获取权限
            
            //用户同意获取数据
            [SHMessageVoiceHUD shareInstance].hudType = 1;
            
            //开始录音
            [self StartiFlySpeech];
            
        }else{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertView *ale = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请开启麦克风权限" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
                [ale show];
            });
        }
    }];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            if (@available(iOS 10.0, *)) {
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
                }];
            }
        }
    }
}
-(void)StartiFlySpeech{
    if(_iFlySpeechRecognizer == nil)
    {
        [self initRecognizer];
    }
    [_iFlySpeechRecognizer cancel];
    
    //Set microphone as audio source
    [_iFlySpeechRecognizer setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
    
    //Set result type
    [_iFlySpeechRecognizer setParameter:@"json" forKey:[IFlySpeechConstant RESULT_TYPE]];
    
    //Set the audio name of saved recording file while is generated in the local storage path of SDK,by default in library/cache.
    [_iFlySpeechRecognizer setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
    
    [_iFlySpeechRecognizer setDelegate:self];
    BOOL ret = [_iFlySpeechRecognizer startListening];
    
    if (ret) {
        NSLog(@"开始识别");
        [[VoiceWaveView ShareVoiceWaveView] StartVoice];
        _textViewText = @"";
        
    }else{
        [[VoiceWaveView ShareVoiceWaveView] EndVoice];
        NSLog(@"启动失败");
    }
}
-(void)initRecognizer{
    if (_iFlySpeechRecognizer == nil) {
        _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
    }
    [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
    //set recognition domain
    [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
    _iFlySpeechRecognizer.delegate = self;
    
    if (_iFlySpeechRecognizer != nil) {
        IATConfig *instance = [IATConfig sharedInstance];
        //set timeout of recording
        [_iFlySpeechRecognizer setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
        //set VAD timeout of end of speech(EOS)
        [_iFlySpeechRecognizer setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
        //set VAD timeout of beginning of speech(BOS)
        [_iFlySpeechRecognizer setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
        //set network timeout
        [_iFlySpeechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
        
        //set sample rate, 16K as a recommended option
        [_iFlySpeechRecognizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
        
        //set language
        [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
        //set accent
        [_iFlySpeechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
        
        //set whether or not to show punctuation in recognition results
        [_iFlySpeechRecognizer setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
        
    }
}
//IFlySpeechRecognizerDelegate协议实现
///识别结果返回代理
- (void) onResults:(NSArray *) results isLast:(BOOL)isLast{
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }
    
    _result =[NSString stringWithFormat:@"%@%@", _textViewText,resultString];
    
    NSString * resultFromJson =  nil;
    
    if([IATConfig sharedInstance].isTranslate){
        
        NSDictionary *resultDic  = [NSJSONSerialization JSONObjectWithData:    //The result type must be utf8, otherwise an unknown error will happen.
                                    [resultString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
        if(resultDic != nil){
            NSDictionary *trans_result = [resultDic objectForKey:@"trans_result"];
            
            if([[IATConfig sharedInstance].language isEqualToString:@"en_us"]){
                NSString *dst = [trans_result objectForKey:@"dst"];
                NSLog(@"dst=%@",dst);
                resultFromJson = [NSString stringWithFormat:@"%@\ndst:%@",resultString,dst];
            }
            else{
                NSString *src = [trans_result objectForKey:@"src"];
                NSLog(@"src=%@",src);
                resultFromJson = [NSString stringWithFormat:@"%@\nsrc:%@",resultString,src];
            }
        }
    }
    else{
        resultFromJson = [ISRDataHelper stringFromJson:resultString];
    }
    
    _textViewText = [NSString stringWithFormat:@"%@%@", _textViewText,resultFromJson];
    
    if (isLast){
        NSLog(@"ISR Results(json)：%@",  self.result);
    }
    NSLog(@"_result=%@",_result);
    NSLog(@"resultFromJson=%@",resultFromJson);
    NSLog(@"isLast=%d,_textView.text=%@",isLast,_textViewText);
    
}
///识别会话结束返回代理
- (void)onCompleted: (IFlySpeechError *) error{
    NSLog(@"识别会话结束返回代理");
    if ([_textViewText isEqualToString:@""]) {
        [SHMessageVoiceHUD shareInstance].hudType = 3;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SHMessageVoiceHUD shareInstance].hudType = 0;
        });
    } else {
//        [SMToastView showMessage:_textViewText];
        [self.delegate chatMessageWithSendText:_textViewText];
        [SHMessageVoiceHUD shareInstance].hudType = 0;
    }
//    [[VoiceWaveView ShareVoiceWaveView] EndVoice];
}

/// 停止录音
-(void)stopListening{
    NSLog(@"停止");
    [_iFlySpeechRecognizer stopListening];
//    [SHMessageVoiceHUD shareInstance].hudType = 0;
    
//    [[VoiceWaveView ShareVoiceWaveView] EndVoice];
}
/// 取消录音录音
-(void)cancel{
    [_iFlySpeechRecognizer cancel];
    NSLog(@"取消");
//    [SHMessageVoiceHUD shareInstance].hudType = 0;
}
///停止录音回调
- (void) onEndOfSpeech{
//    [SHMessageVoiceHUD shareInstance].hudType = 0;
    NSLog(@"停止录音回调");
}
///开始录音回调
- (void) onBeginOfSpeech{
    NSLog(@"开始录音回调");
}
///音量回调函数
- (void) onVolumeChanged: (int)volume{
    NSLog(@"音量%d",volume);
    if (volume == 0) {
        [[SHMessageVoiceHUD shareInstance] showVoiceMeters:0];
    } else if (volume > 0 && volume <= 4) {
        [[SHMessageVoiceHUD shareInstance] showVoiceMeters:1];
    } else if (volume > 4 && volume <= 8) {
        [[SHMessageVoiceHUD shareInstance] showVoiceMeters:2];
    } else if (volume > 8 && volume <= 12) {
        [[SHMessageVoiceHUD shareInstance] showVoiceMeters:3];
    } else if (volume > 12 && volume <= 16) {
        [[SHMessageVoiceHUD shareInstance] showVoiceMeters:4];
    } else if (volume > 16 && volume <= 20) {
        [[SHMessageVoiceHUD shareInstance] showVoiceMeters:5];
    } else if (volume > 20 && volume <= 24) {
        [[SHMessageVoiceHUD shareInstance] showVoiceMeters:6];
    } else if (volume > 24 && volume <= 28) {
        [[SHMessageVoiceHUD shareInstance] showVoiceMeters:7];
    } else {
        [[SHMessageVoiceHUD shareInstance] showVoiceMeters:7];
    }
    
}
///会话取消回调
- (void) onCancel{
    NSLog(@"会话取消回调");
}
@end
