#import "Core.h"
#import "RTKLogger.h"

@implementation Core

RCT_EXPORT_MODULE()

// Example method
// See // https://reactnative.dev/docs/native-modules-ios
RCT_REMAP_METHOD(multiply,
                 multiplyWithA:(nonnull NSNumber*)a withB:(nonnull NSNumber*)b
                 withResolver:(RCTPromiseResolveBlock)resolve
                 withRejecter:(RCTPromiseRejectBlock)reject)
{
  NSNumber *result = @([a floatValue] * [b floatValue]);

  resolve(result);
}

RCT_EXPORT_SYNCHRONOUS_TYPED_METHOD(NSString*, getRandomBase64:(NSUInteger)byteLength) {
    NSMutableData *data = [NSMutableData dataWithLength:byteLength];
    int result = SecRandomCopyBytes(kSecRandomDefault, byteLength, data.mutableBytes);
    if (result != errSecSuccess) {
        @throw([NSException exceptionWithName:@"NO_RANDOM_BYTES" reason:@"Failed to aquire secure random bytes" userInfo:nil]);
    }
    return [data base64EncodedStringWithOptions:0];
}

#pragma mark - RTKLogger Control

RCT_EXPORT_METHOD(enableLogging)
{
    // Enable Objective-C logger
    [RTKLogger sharedInstance].loggingEnabled = YES;
    
    [RTKLogger info:@"RTKLogger logging enabled"];
}

RCT_EXPORT_METHOD(disableLogging)
{
    [RTKLogger info:@"RTKLogger logging disabled"];
    
    // Disable Objective-C logger
    [RTKLogger sharedInstance].loggingEnabled = NO;
}

RCT_EXPORT_METHOD(setLoggingEnabled:(BOOL)enabled)
{
    // Set for Objective-C logger
    [RTKLogger sharedInstance].loggingEnabled = enabled;
    
    [RTKLogger info:@"RTKLogger logging %@", enabled ? @"enabled" : @"disabled"];
}

RCT_EXPORT_METHOD(setLogLevel:(NSInteger)level)
{
    // Set for Objective-C logger
    [RTKLogger sharedInstance].minimumLogLevel = (RTKLogLevel)level;
    
    [RTKLogger info:@"RTKLogger minimum log level set to: %ld", (long)level];
}

RCT_EXPORT_METHOD(getLoggingEnabled:(RCTPromiseResolveBlock)resolve
                            reject:(RCTPromiseRejectBlock)reject)
{
    BOOL enabled = [RTKLogger sharedInstance].loggingEnabled;
    resolve(@(enabled));
}

@end
