#import "RookSourcesModule.h"
#import "RookSDK/RookSDK-Swift.h"
#import "RCTConvert.h"

@implementation RookSourcesModule

RCT_EXPORT_MODULE()

DataSourceManagerObjc *sourceManager;
UserManager* sourceUserManager;

- (void) checkUserInstance {
  if (sourceUserManager == nil) sourceUserManager = [UserManager new];
}

- (void) checkSourcesInstance {
  if (sourceManager == nil) sourceManager = [DataSourceManagerObjc new];
}

/**
 * check the authorizers and retrieve the sources available and configured 
 *
 * @param resolve A block called with a boolean value indicating whether the result.
 * @param reject A block called if an error occurs, such as Apple Health not being installed.
 */
RCT_EXPORT_METHOD(getAvailableDataSources: (NSDictionary *) options
                  resolve:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    [self checkSourcesInstance];

    NSString *redirectURL = [RCTConvert NSString:options[@"redirectURL"]];
    
    [sourceManager getAvailableDataSourcesWithRedirectURL:redirectURL
                                               completion:^(NSArray<NSDictionary<NSString *,id> *> * _Nullable sources, NSError * _Nullable error) {
        if (error) {
            reject(error.description, error.localizedDescription, error);
            return;
        }

        if (sources) {
            resolve(sources);
            return;
        }
    
        resolve([NSDictionary dictionary]);
    }];
}

/**
 * Check the authorizers and present a default view.
 *
 * @param resolve A block called with a boolean value indicating whether the result is.
 * @param reject A block called if an error occurs, such as Apple Health not being installed.
 */
RCT_EXPORT_METHOD(presentDataSourceView: (NSDictionary *) options
                  resolve:(RCTPromiseResolveBlock)resolve
                  reject:(RCTPromiseRejectBlock)reject) {
    [self checkSourcesInstance];

    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *redirectURL = [RCTConvert NSString:options[@"redirectURL"]];
        
        [sourceManager presentDataSourceViewWithRedirectURL:redirectURL completion:^(BOOL succeed, NSError * _Nullable error) {
            if (error) {
                reject(error.description, error.localizedDescription, error);
                return;
            }
            
            resolve(@(succeed));
        }];
    });
}

/**
 * Revoke the access to a API source 
 *
 * @param resolve A block called with a boolean value indicating whether the result is.
 * @param reject A block called if an error occurs, such as Apple Health not being installed.
 */
RCT_EXPORT_METHOD(revokeDataSource: (NSString *) source
                 resolve:(RCTPromiseResolveBlock)resolve
                 reject:(RCTPromiseRejectBlock)reject) {
    
    [self checkUserInstance];

   dispatch_async(dispatch_get_main_queue(), ^{
       [sourceUserManager revokeDataSourceWithDataSource:source completion:^(BOOL succeed, NSError * _Nullable error) {
           if (error) {
               reject(error.description, error.localizedDescription, error);
               return;
           }
           
           resolve(@(succeed));
       }];
     });
}

RCT_EXPORT_METHOD(getAuthorizedDataSources: (RCTPromiseResolveBlock) resolve
                  reject:(RCTPromiseRejectBlock)reject ) {
  
  [self checkSourcesInstance];

  [sourceManager getAuthorizedDataSourcesWithCompletion:^(NSArray<NSDictionary<NSString *,id> *> * _Nullable sources, NSError * _Nullable error) {
    if(error) {
      reject(error.description, error.localizedDescription, error);
      return;
    }
    
    resolve(sources);
  }];
}

RCT_EXPORT_METHOD(getDataSourceAuthorizer:(NSDictionary *)params
                  resolve:(RCTPromiseResolveBlock) resolve
                  reject:(RCTPromiseRejectBlock)reject ) {
  
  [self checkSourcesInstance];

  NSString * source = [RCTConvert NSString:params[@"dataSource"]];
  NSString * redirect = [RCTConvert NSString:params[@"redirectURL"]];
  
  [sourceManager getDataSourceAuthorizerWithDataSource:source
                                           redirectUrl:redirect
                                            completion:^(NSDictionary<NSString *,id> * _Nullable sources, NSError * _Nullable error) {
    if(error) {
      reject(error.description, error.localizedDescription, error);
      return;
    }
    
    resolve(sources);
    
  }];
}
@end
