//
//  NativeManager.m
//  AwesomeProject
//
//  Created by 谭锦标 on 2023/1/11.
//

#import "NativeManager.h"
#if __has_include(<React/RCTBridge.h>)
#import <React/RCTEventDispatcher.h>
#import <React/RCTRootView.h>
#import <React/RCTBridge.h>
#import <React/RCTLog.h>

#elif __has_include("RCTBridge.h")
#import "RCTEventDispatcher.h"
#import "RCTRootView.h"
#import "RCTBridge.h"
#import "RCTLog.h"
#elif __has_include("React/RCTBridge.h")
#import "React/RCTEventDispatcher.h"
#import "React/RCTRootView.h"
#import "React/RCTBridge.h"
#import "React/RCTLog.h"
#endif

#import <XtionAISDK/XtionAISDK.h>

@implementation NativeManager

+ (void)initialize

{

  if (self != [RCTEventEmitter class]) {

    RCTAssert(RCTClassOverridesInstanceMethod(self,@selector(supportedEvents)),

              @"You must override the `supportedEvents` method of %@", self);

  }

}

/// 重写方法，定义支持的事件集合
- (NSArray<NSString *> *)supportedEvents {
  return @[@"sendEventToRn"];
}

- (void)startObserving{
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sendCustomEvent:) name:@"notificationName1" object:nil];
}

/// 接收通知的方法，接收到通知后发送事件到RN端。RN端接收到事件后可以进行相应的逻辑处理或界面跳转
- (void)sendCustomEvent:(NSNotification *)notification {
  NSDictionary *dict = notification.object;
  
  [self sendEventWithName:@"sendEventToRn" body:[self convertToJsonData:dict]];
}

- (void)stopObserving {

    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (dispatch_queue_t)methodQueue
{
    dispatch_queue_t queuet = dispatch_queue_create("com.facebook.React.AsyncLocalStorageQueue", DISPATCH_QUEUE_SERIAL);
    
    dispatch_queue_t referQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); //参考优先级
    
    dispatch_set_target_queue(queuet, referQueue);
    
  return queuet;
}

-(NSString *)convertToJsonData:(NSDictionary *)dict {
  NSError *error;
  NSData * jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingSortedKeys error:&error];
  NSString *jsonString;
  if(jsonData) {
    jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  }
  return jsonString;
}

RCT_EXPORT_MODULE(NativeManager);

RCT_EXPORT_METHOD(callNative:(NSString *)functionName data:(id)data resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject){
  if([functionName isEqualToString:@"Init"]){
    NSLog(@"Init,%@",data);
    
    if([data isKindOfClass:NSDictionary.class]){
      NSString *accessKey = [data objectForKey:@"accessKey"];
      NSString *account = [data objectForKey:@"account"];
      NSString *accountId = [data objectForKey:@"accountId"];
      
      [[XtionAIShareManager sharedManager] SDKHost:account accessKey:accessKey result:^(NSDictionary * _Nonnull dict) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"notificationName1" object:dict];
      }];
      
      
    } else {
      [[NSNotificationCenter defaultCenter]postNotificationName:@"notificationName1" object: @{@"code":@"999",@"data":@"",@"message":@"初始化失败"}];
    }
    
    
  } else if([functionName isEqualToString:@"Camera"]){
    NSLog(@"Camera,%@",data);
    
    if([data isKindOfClass:NSDictionary.class]){
        
      
        NSString *dataRetained = @"clear";
        if([data objectForKey:@"dataRetainedMode"]){
            if([[data objectForKey:@"dataRetainedMode"] isKindOfClass:[NSString class]]){
                dataRetained = [data objectForKey:@"dataRetainedMode"];
                if([dataRetained isEqualToString:@"retain"] || [dataRetained isEqualToString:@"clear"]){}else {
                    resolve(@[
                        [self convertToJsonData:@{@"code":@"999",@"data":@"",@"message":@"参数错误,dataRetained值有误"}]
                    ]);
                    return;
                }} else {
                    resolve(@[
                        [self convertToJsonData:@{@"code":@"999",@"data":@"",@"message":@"参数错误,dataRetained值有误"}]
                    ]);
                    return;
            }
        }
        BOOL isCkeckKey = YES;
        NSArray *cameraModeArray = @[];
        if([data objectForKey:@"cameraMode"]){
            if([[data objectForKey:@"cameraMode"] isKindOfClass:[NSArray class]]){
                cameraModeArray = [data objectForKey:@"cameraMode"];
                for (NSDictionary *cameraMode in cameraModeArray) {
                    if([cameraMode objectForKey:@"mode"] ){
                        if( [[cameraMode objectForKey:@"mode"] isKindOfClass:[NSString class]]){
                            
                            if([[cameraMode objectForKey:@"mode"]  isEqualToString:@"continuous"] || [[cameraMode objectForKey:@"mode"]  isEqualToString:@"single"] || [[cameraMode objectForKey:@"mode"]  isEqualToString:@"video"] || [[cameraMode objectForKey:@"mode"]  isEqualToString:@"panorama"] || [[cameraMode objectForKey:@"mode"]  isEqualToString:@"panoramaPlus"]){ }else {
                                NSLog(@"%@", [cameraMode objectForKey:@"mode"]);
                                isCkeckKey = NO;
                            }
                        }  else {
                            isCkeckKey = NO;
                        }} else {
                            isCkeckKey = NO;
                        }
                    
                    if([cameraMode objectForKey:@"flashMode"]){
                        if( [[cameraMode objectForKey:@"flashMode"] isKindOfClass:[NSString class]]){
                            if([[cameraMode objectForKey:@"flashMode"]  isEqualToString:@"on"] || [[cameraMode objectForKey:@"flashMode"]  isEqualToString:@"off"] || [[cameraMode objectForKey:@"flashMode"]  isEqualToString:@"auto"]){}else {
                                isCkeckKey = NO;
                            }

                        } else {
                            isCkeckKey = NO;
                        }}
                    
                    if([cameraMode objectForKey:@"type"]){
                        if([[cameraMode objectForKey:@"type"] isKindOfClass:[NSString class]]){
                            if([[cameraMode objectForKey:@"type"]  isEqualToString:@"back"] || [[cameraMode objectForKey:@"type"]  isEqualToString:@"front"]){}else {
                                isCkeckKey = NO;
                            }
                        } else {
                            isCkeckKey = NO;
                        }}
                    
                    if([cameraMode objectForKey:@"quality"]){
                        if( [[cameraMode objectForKey:@"quality"] isKindOfClass:[NSNumber class]]){
                        } else {
                            isCkeckKey = NO;
                        }}
                    
                    if([cameraMode objectForKey:@"quantity"]){
                        if([[cameraMode objectForKey:@"quantity"] isKindOfClass:[NSNumber class]]){
                        } else {
                            isCkeckKey = NO;
                        }}
                    
                    if([cameraMode objectForKey:@"recTime"] ){
                        if([[cameraMode objectForKey:@"recTime"] isKindOfClass:[NSNumber class]]){
                        } else {
                            isCkeckKey = NO;
                        }}
                    
                    if([cameraMode objectForKey:@"videoQuality"] ){
                        if([[cameraMode objectForKey:@"videoQuality"] isKindOfClass:[NSNumber class]]){
                        } else {
                            isCkeckKey = NO;
                        }}
                    
                    if([cameraMode objectForKey:@"showPreview"] ){
                        if([[cameraMode objectForKey:@"showPreview"] isKindOfClass:[NSNumber class]]){
                            if([[cameraMode objectForKey:@"showPreview"] intValue] == 0 || [[cameraMode objectForKey:@"showPreview"] intValue] == 1 ){} else {
                                isCkeckKey = NO;
                            }
                        } else {
                            isCkeckKey = NO;
                        }}
                }
                    
                } else {
                    resolve(@[
                        [self convertToJsonData:@{@"code":@"999",@"data":@"",@"message":@"参数错误,cameraMode值有误"}]
                    ]);
                    return;
            }
            
            if(!isCkeckKey){
                resolve(@[
                    [self convertToJsonData:@{@"code":@"999",@"data":@"",@"message":@"参数错误,cameraMode值有误"}]
                ]);
                return;
            }
        }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [[XtionAIShareManager sharedManager] getFullSencePictures:cameraModeArray dataRetained:dataRetained result:^(NSDictionary * _Nonnull dict, BOOL isFinished) {
            if(isFinished){
              
              resolve(@[
                [self convertToJsonData:dict]
              ]);
            } else {
              resolve(@[
                [self convertToJsonData:dict]
              ]);
            }
        }];
     
      
    });
    } else {
      resolve(@[
        [self convertToJsonData:@{@"code":@"999",@"data":@"",@"message":@"入参格式不正确"}]
      ]);
    }
  } else if([functionName isEqualToString:@"isRemake"]){
    NSLog(@"isRemake,%@",data);
    if([data isKindOfClass:NSArray.class]){
      [[XtionAIShareManager sharedManager] getFakePhotos:data result:^(NSDictionary * _Nonnull dict) {
        resolve(@[
          [self convertToJsonData:dict]
        ]);
      }];
      
    } else {
      resolve(@[
        [self convertToJsonData:@{@"code":@"999",@"data":@"",@"message":@"入参格式不正确"}]
      ]);
    }
  } else {
    resolve(@[
      [self convertToJsonData:@{@"code":@"101",@"data":@"",@"message":@"调用方法(API)不存在"}]
    ]);
  }
}

@end
