// Bridge between React and iOS

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

// MARK: - Utils
NSString *convertToString(id value) {
    if ([value isKindOfClass:[NSString class]]) {
        return (NSString *)value;
    } else {
        return [value description];
    }
}

// A function that takes an NSException object as input and creates an
// NSError object based on the exception information. It creates a dictionary with localized
// description and failure reason keys using the exception's name and reason properties. Then, it
// creates an NSError object with a custom domain, error code, and the dictionary of error information,
// and returns it.
NSError *errorFromException(NSException *exception) {
    NSMutableDictionary *errorInfo = [NSMutableDictionary dictionary];
    errorInfo[NSLocalizedDescriptionKey] = [NSString stringWithFormat:@"Exception caught: %@", exception.name];
    errorInfo[NSLocalizedFailureReasonErrorKey] = exception.reason;

    return [NSError errorWithDomain:@"com.mydomain.MyApp" code:500 userInfo:errorInfo];
}

// MARK: - Module
@implementation RookSdkAppleHealth
{
  bool hasListeners;
}

RCT_EXPORT_MODULE()

// Will be called when this module's first listener is added.
-(void)startObserving {
    hasListeners = YES;
  
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveTestNotification:)
                                                 name:@"kRookErrorBackground"
                                               object:nil];
}

// Will be called when this module's last listener is removed, or on dealloc.
-(void)stopObserving {
    hasListeners = NO;
  
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

// Define the events type that will be broadcasted 
- (NSArray<NSString *> *)supportedEvents {
    return @[@"ROOK_NOTIFICATION"];
}

// The above code is an Objective-C method that receives a notification and checks if the notification
// name is "kRookErrorBackground". If it is, it extracts information from the notification's userInfo
// dictionary, specifically an error object. It then creates a dictionary message containing the type,
// message, and code extracted from the error object. Finally, if there are listeners registered, it
// sends an event with the message dictionary to a specific event name "ROOK_NOTIFICATION".
- (void) receiveTestNotification:(NSNotification *) notification
{
  if ([[notification name] isEqualToString:@"kRookErrorBackground"]) {
     NSDictionary<NSString*, NSError *> *notificationInfo = [[notification userInfo] mutableCopy];
    
    NSMutableDictionary *message = [[NSMutableDictionary alloc] init];
    message[@"type"] = @"ROOK_APPLE_HEALTH_BACKGROUND_ERROR";
    message[@"message"] = notificationInfo[@"Error"].localizedDescription;
    message[@"code"] = notificationInfo[@"Error"].description;
    
    if (hasListeners)
      [self sendEventWithName:@"ROOK_NOTIFICATION" body: message];
  }
}

/**
 * Internal method to send messages to broadcast channel 
 *
 * @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.
 */
// ROOK_BACKGROUND_ENABLED
RCT_EXPORT_METHOD(sendMessageToBroadcast: (NSDictionary *) message
                  resolve: (RCTPromiseResolveBlock) resolve
                  reject: (RCTPromiseRejectBlock) reject) {
    if(hasListeners) {
        [self sendEventWithName:@"ROOK_NOTIFICATION" body:message];
    }
}

@end

