#import <React/RCTBridge+Private.h>
#import <ReactCommon/CallInvoker.h>
#import "DittoRNSDK.h"
#import "main.h"

using namespace facebook::jsi;

@interface RCTBridge (BridgeWithCallInvoker)
- (std::shared_ptr<facebook::react::CallInvoker>)jsCallInvoker;
@end

@implementation DittoRNSDK

using namespace facebook::jsi;

RCT_EXPORT_MODULE()

+ (BOOL)requiresMainQueueSetup
{
  return YES;
}

RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(install)
{
  RCTBridge* bridge = [RCTBridge currentBridge];
  RCTCxxBridge* cxxBridge = (RCTCxxBridge*)bridge;
  Runtime &jsiRuntime = *((Runtime *) cxxBridge.runtime);

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *defaultDirectory = [paths firstObject];
  Object parameters(jsiRuntime);
  parameters.setProperty(jsiRuntime, "defaultDirectory", String::createFromUtf8(jsiRuntime, [defaultDirectory UTF8String]));
  
  auto callInvoker = cxxBridge.jsCallInvoker;

  sharedjsi::install(jsiRuntime, callInvoker, parameters);
  install(jsiRuntime);

  return @true;
}

static void install(Runtime &jsiRuntime) {
  auto defaultDeviceName = Function::createFromHostFunction(jsiRuntime,
                                                            PropNameID::forAscii(jsiRuntime,
                                                                                 "defaultDeviceName"),
                                                            0,
                                                            [](Runtime &runtime,
                                                               const Value &thisValue,
                                                               const Value *arguments,
                                                               size_t count) -> Value {

    return String::createFromUtf8(runtime, [[[UIDevice currentDevice] name] UTF8String]);
  });

  jsiRuntime.global().setProperty(jsiRuntime, "defaultDeviceName", std::move(defaultDeviceName));
}

@end
