import Foundation   
import UIKit
import IppoPay

@objc(IppoPayment)
class IppoPayment: NSObject, RCTBridgeModule, IppopayDelegate  {

  var callBack: RCTResponseSenderBlock?
    
    public static func moduleName() -> String! {
      return "IppoPayment"
    }
    
    override public init() {
    }
    
  @objc func initSDK(_ publicKey: String) {
        DispatchQueue.main.async {
          Ippopay.initSDK(publicKey: publicKey, withDelegate: self)
        }
    }
  
  @objc public static func requiresMainQueueSetup() -> Bool {
      return false
  }

  @objc func makePayment(_ orderData: String, callBack: @escaping RCTResponseSenderBlock) {
      self.callBack = callBack
        var dictValue = convertToDictionary(text: orderData)
          var order = OrderData()
          order.orderId = dictValue?["order_id"] as? String
      DispatchQueue.main.async {
        Ippopay.makePayment(orderData: order)
      }
        
    }

      func convertToDictionary(text: String) -> [String: Any]? {
          if let data = text.data(using: .utf8) {
              do {
                  return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
              } catch {
                  print(error.localizedDescription)
              }
          }
          return nil
      }

      internal func onPaymentError(descriptionOfError: String) {
          print(descriptionOfError)
          let result = ["success" : false, "message" : descriptionOfError] as [String : Any]
          if let theJSONData = try? JSONSerialization.data(withJSONObject: result,options: []) {
              let theJSONText = String(data: theJSONData, encoding: .utf8)
              print("JSON string = \(theJSONText!)")
              callBack!([theJSONText])
          }
      }

      internal func onPaymentSuccess(paymentId: String) {
        print("paymentId::::::::::")
        let result = ["success" : true, "message" : "Payment Successful", "transaction_id": paymentId] as [String : Any]
          if let theJSONData = try? JSONSerialization.data(withJSONObject: result,options: []) {
              let theJSONText = String(data: theJSONData, encoding: .utf8)
              print("JSON string = \(theJSONText!)")
              callBack!([theJSONText])
          }
      }

    
  }
