#import "XFlySpeechUnderstander.h"
#import <QuartzCore/QuartzCore.h>
#import "iflyMSC/IFlyMSC.h"
#import "IATConfig.h"
#import "RCTEventDispatcher.h"

@implementation XFlySpeechUnderstander
@synthesize bridge = _bridge;


RCT_EXPORT_MODULE()


- (id)init
{
    self = [super init];
    if (self)
    {
        _iFlySpeechUnderstander = [IFlySpeechUnderstander sharedInstance];
        _iFlySpeechUnderstander.delegate = self;
        [_iFlySpeechUnderstander cancel];//终止语义
        [_iFlySpeechUnderstander setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
    }
    return self;
}

RCT_EXPORT_METHOD(sharedUnderstanderInstance)
{
    _iFlySpeechUnderstander = [IFlySpeechUnderstander sharedInstance];
    _iFlySpeechUnderstander.delegate = self;
    [_iFlySpeechUnderstander cancel];//终止语义
    [_iFlySpeechUnderstander setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
}

RCT_EXPORT_METHOD(textUnderstander:(NSString *)text)
{
    if(self.iFlyUnderStand == nil)
    {
        self.iFlyUnderStand = [[IFlyTextUnderstander alloc] init];
    }
    
    //启动文本语义搜索
    [self.iFlyUnderStand understandText:text withCompletionHandler:^(NSString* restult, IFlySpeechError* error)
     {
         NSLog(@"result is : %@",restult);
         if (error!=nil && error.errorCode!=0) {
             
             NSString* errorText = [NSString stringWithFormat:@"发生错误：%d %@",error.errorCode,error.errorDesc];
             
         }
     }];
}

RCT_EXPORT_METHOD(speechUnderstander)
{
    if (_iFlySpeechUnderstander == nil) {
        [self initRecognizer];
    }
    
    [_iFlySpeechUnderstander setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
    bool ret = [_iFlySpeechUnderstander startListening];
    if (ret) {
        NSLog(@"启动识别服务");
        self.isCanceled = NO;
    }
    else
    {
        NSLog(@"启动识别服务失败，请稍后重试");//可能是上次请求未结束
    }
}

RCT_EXPORT_METHOD(stopListening)
{
    [_iFlySpeechUnderstander stopListening];
}

RCT_EXPORT_METHOD(cancel)
{
    [_iFlySpeechUnderstander cancel];
}

/**
 音量变化回调
 volume 录音的音量，音量范围0~30
 ****/
- (void) onVolumeChanged: (int)volume
{
    if (self.isCanceled) {
        return;
    }
    
    [self.bridge.eventDispatcher sendAppEventWithName:@"IFly"
                                                 body:@{
                                                        @"event": @"onVolumeChanged",
                                                        @"from": @"SpeechUnderstander",
                                                        @"volume": @(volume)
                                                        }];
}

/**
 开始识别回调
 ****/
- (void) onBeginOfSpeech
{
    [self.bridge.eventDispatcher sendAppEventWithName:@"IFly"
                                                 body:@{
                                                        @"event": @"onBeginOfSpeech",
                                                        @"from": @"SpeechUnderstander",
                                                        }];
}

/**
 停止录音回调
 ****/
- (void) onEndOfSpeech
{
    [self.bridge.eventDispatcher sendAppEventWithName:@"IFly"
                                                 body:@{
                                                        @"event": @"onEndOfSpeech",
                                                        @"from": @"SpeechUnderstander",
                                                        }];
}


/**
 语义理解服务结束回调（注：无论是否正确都会回调）
 error.errorCode =
 0     听写正确
 other 听写出错
 ****/
- (void) onError:(IFlySpeechError *) error
{
    
    [self.bridge.eventDispatcher sendAppEventWithName:@"IFly"
                                                 body:@{
                                                        @"event": @"onError",
                                                        @"from": @"SpeechUnderstander",
                                                        @"errorCode": @(error.errorCode),
                                                        @"errorDesc": error.errorDesc
                                                        }];
}


/**
 语义理解结果回调
 result 识别结果，NSArray的第一个元素为NSDictionary，NSDictionary的key为识别结果，value为置信度
 isLast：表示最后一次
 ****/
- (void) onResults:(NSArray *) results isLast:(BOOL)isLast
{
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = results [0];
    
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    
    [self.bridge.eventDispatcher sendAppEventWithName:@"IFly"
                                                 body:@{
                                                        @"event": @"onResults",
                                                        @"from": @"SpeechUnderstander",
                                                        @"result": result,
                                                        }];
}

/**
 取消回调
 当调用了[_iFlySpeechUnderstander cancel]后，会回调此函数，
 ****/
- (void) onCancel
{
    [self.bridge.eventDispatcher sendAppEventWithName:@"IFly"
                                                 body:@{
                                                        @"event": @"onCancel",
                                                        @"from": @"SpeechUnderstander",
                                                        }];
}


/**
 设置识别参数
 ****/
-(void)initRecognizer
{
    //语义理解单例
    if (_iFlySpeechUnderstander == nil) {
        _iFlySpeechUnderstander = [IFlySpeechUnderstander sharedInstance];
    }
    
    _iFlySpeechUnderstander.delegate = self;
    
    if (_iFlySpeechUnderstander != nil) {
        IATConfig *instance = [IATConfig sharedInstance];
        
        //参数意义与IATViewController保持一致，详情可以参照其解释
        [_iFlySpeechUnderstander setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
        [_iFlySpeechUnderstander setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
        [_iFlySpeechUnderstander setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
        [_iFlySpeechUnderstander setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
        
        if ([instance.language isEqualToString:[IATConfig chinese]]) {
            [_iFlySpeechUnderstander setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            [_iFlySpeechUnderstander setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
        }else if ([instance.language isEqualToString:[IATConfig english]]) {
            [_iFlySpeechUnderstander setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
        }
        [_iFlySpeechUnderstander setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
    }
}

@end
