#import "HiBaiduTts.h"
#import "HiSpeechSynthesizer.h"
#import <Foundation/Foundation.h>

@interface HiBaiduTts () <HiSpeechSynthesizerDelegate>

@property(nonatomic,strong)HiSpeechSynthesizer *speechSynthesizer;

@end

@implementation HiBaiduTts

- (void)willRemoveAllTexts:(nonnull NSArray *)texts error:(nullable NSError *)error {
    for (int i=0; i<[texts count]; i++) {
        NSDictionary *text = texts[i];
        RCTPromiseRejectBlock reject = [text objectForKey:@"reject"];
        if(reject)reject(@"error",@"cancel",error);
    }
    
}
- (void)didEndSpeakText:(nonnull NSDictionary *)text{
    RCTPromiseResolveBlock resolve = [text objectForKey:@"resolve"];
    if(resolve)resolve(@{@"success" : @(true)});
}


RCT_EXPORT_MODULE()

// Example method
// See // https://reactnative.dev/docs/native-modules-ios
RCT_EXPORT_METHOD(initSDK:(NSString *)apiKey secretKey:(NSString *)secretKey appId:(NSString *)appId)
{
    if(!_speechSynthesizer){
        _speechSynthesizer = [[HiSpeechSynthesizer alloc] initApiKey:apiKey secretKey:secretKey];
        _speechSynthesizer.delegate = self;
        [_speechSynthesizer setSpeed:@(6)];
    }
}

RCT_REMAP_METHOD(speak,text:(NSString *)text resolve:(RCTPromiseResolveBlock )resolve reject:(RCTPromiseRejectBlock )reject)
{
    if(_speechSynthesizer){
        NSMutableDictionary *dic = [_speechSynthesizer synthesizeText:text];
        if(dic){
            if(resolve){
                [dic setObject:[resolve copy] forKey:@"resolve"];
                if(reject)[dic setObject:[reject copy]forKey:@"reject"];
            }
        }
        else {
            if(reject) reject(@"speak fail!", nil, nil);
        }
    }
}

RCT_EXPORT_METHOD(setSpeaker:(NSString *)speaker)
{
    if(_speechSynthesizer){
        [_speechSynthesizer setSpeaker:speaker];
    }
}

RCT_EXPORT_METHOD(setVolume:(nonnull NSNumber *)value)
{
    if(_speechSynthesizer){
        [_speechSynthesizer setVolume:value];
    }
}

RCT_EXPORT_METHOD(setSpeed:(nonnull NSNumber *)value)
{
    if(_speechSynthesizer){
        [_speechSynthesizer setSpeed:value];
    }
}

RCT_EXPORT_METHOD(setPitch:(nonnull NSNumber *)value)
{
    if(_speechSynthesizer){
        [_speechSynthesizer setPitch:value];
    }
}

RCT_EXPORT_METHOD(setAudioSessionCategory:(nonnull NSNumber *)category)
{
    if(_speechSynthesizer){
        [_speechSynthesizer setAudioSessionCategory:category];
    }
}

RCT_EXPORT_METHOD(setAudioSessionEnable:(nonnull NSNumber *)value)
{
    if(_speechSynthesizer){
        [_speechSynthesizer setAudioSessionEnable:value];
    }
}



RCT_EXPORT_METHOD(cancel)
{
    if(_speechSynthesizer){
        [_speechSynthesizer cancel];
    }
}


- (dispatch_queue_t)methodQueue
{
  return dispatch_get_main_queue();
}

@end
