import Foundation
import RLTMXProfiling
import RLTMXProfilingConnections

@objc(CybersourceFingerprintSdk)
class CybersourceFingerprintSdk: NSObject {
 var profile: RLTMXProfiling?
  var sessionID: String = ""
  @objc(multiply:withB:withResolver:withRejecter:)
  func multiply(a: Float, b: Float, resolve:RCTPromiseResolveBlock,reject:RCTPromiseRejectBlock) -> Void {
    resolve(a*b)
  }

  @objc(initialize:serverUrl:resolve:reject:)
  func initialize(_ orgId: String, serverUrl: String, resolve: RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) -> Void{
    print(" INSIDE INITIALIZE")

    if(self.profile != nil){
      let error = NSError(domain: "", code: 200, userInfo: nil)
      rejecter("SDK","SDK has been initialized already", error)
      return;
    }

    let profilingConnections: RLTMXProfilingConnections = RLTMXProfilingConnections.init()
    profilingConnections.connectionTimeout = 20;
    profilingConnections.connectionRetryCount = 2;
    self.profile = RLTMXProfiling.sharedInstance()
    profile!.configure(configData:[
          RLTMXOrgID: orgId,
          RLTMXFingerprintServer: serverUrl,
          RLTMXProfilingConnectionsInstance: profilingConnections
          //RLTMXProfileTimeout:  60, // profile timeout in seconds
        ])
        print("===============")
        print(profile)
        print("SDK initialized")
        resolve(true)
  }

  @objc(setSessionID:resolve:reject:)
  func setSessionID(_ sessionid: String, resolve: @escaping RCTPromiseResolveBlock, rejecter: RCTPromiseRejectBlock) -> Void{
    print("Starting profiler with \(sessionid)")
    let customAttributes : [String : String] = [RLTMXSessionID: sessionid]

    if self.profile != nil{
      profile!.profileDevice(profileOptions:customAttributes, callbackBlock:
      {(result: [AnyHashable : Any]?) -> Void in
        let results: NSDictionary! = result! as NSDictionary
        let status: RLTMXStatusCode = RLTMXStatusCode(rawValue:(results.value(forKey: RLTMXProfileStatus) as! NSNumber).intValue)!
        let sessionID = results.value(forKey: RLTMXSessionID) as! String
        self.sessionID = sessionID
        // if(status == .ok)
        // Return status code and sessionID
        resolve([
          "status": status.rawValue,
          "sessionId": sessionID,
          "statusDesc": "..."
        ])
      }) // end profileHandle function call
    }
    else{
      let error = NSError(domain: "", code: 200, userInfo: nil)
      rejecter("profile","SDK hasn't been initialized yet", error)
    }

  }
}
