import Foundation   //objc
import UIKit
import FoloosiSdk

@objc(Foloosi)
class Foloosi:NSObject, RCTBridgeModule, FoloosiDelegate {


    var callBack: RCTResponseSenderBlock?
    
    public static func moduleName() -> String! {
      return "Foloosi"
    }
    
    override public init() {
    }
    
    
//    @objc func initSDK(_ publicKey: String) {
//      DispatchQueue.main.async {
//        FoloosiPay.initSDK(merchantKey: publicKey, withDelegate: self)
//      }
//    }
//
    
    @objc func initSDK(_ initData: String) {
        let dictValue = convertToDictionary(text: initData)
        let initObject = InitData()
        initObject.merchantKey=dictValue?["merchantKey"]as? String
        initObject.customColor = dictValue?["customColor"]as? String
        
        
      DispatchQueue.main.async {
        FoloosiPay.initSDK(initData: initObject, withDelegate: self)
      }
        
    }
    
    @objc public static func requiresMainQueueSetup() -> Bool {
      return false
    }
    
    
    @objc func makePayment(_ orderData: String, callBack: @escaping RCTResponseSenderBlock) {
      self.callBack = callBack
      let dictValue = convertToDictionary(text: orderData)
      let order = OrderData()
      let customer = Customer()
      order.orderId = dictValue?["orderId"] as? String
      order.currencyCode=dictValue?["currencyCode"] as? String
     // order.customColor = dictValue?["customColor"] as? String
      order.orderDescription = dictValue?["orderDescription"] as? String
      order.customerUniqueReference = dictValue?["customerUniqueReference"] as? String
      order.country = dictValue?["country"] as? String
      order.state=dictValue?["state"] as? String
      order.postalCode=dictValue?["postalCode"] as? String
      order.orderAmount =  dictValue?["orderAmount"] as? Double
      
      let customerDict = dictValue?["customer"] as? [String:Any]
      customer.customerName = customerDict?["name"] as? String
      customer.customerEmail = customerDict?["email"] as? String
      customer.customerPhoneNumber = customerDict?["mobile"] as? String
      customer.customerCity = customerDict?["city"] as? String
      customer.customerAddress = customerDict?["address"] as? String
      order.customer = customer
      
      
      DispatchQueue.main.async {
        FoloosiPay.makePayment(orderData: order)
      }
    }
    
    @objc func makePaymentWithReferenceToken(_ referenceToken: String, callBack: @escaping RCTResponseSenderBlock) {
      self.callBack = callBack
      DispatchQueue.main.async {
        FoloosiPay.makePaymentWithReferenceToken(referenceToken)
      }
    }
    
    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, transactionId: String, responseCode: String) {
      print(descriptionOfError)
      let result = ["success" : false, "message" : descriptionOfError, "transaction_id": transactionId, "response_code": responseCode] 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(transactionId: String, responseCode: String) {
      let result = ["success" : true, "message" : "Payment Successful", "transaction_id": transactionId, "response_code": responseCode] 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])
      }
    }
    
//    func onPaymentError(descriptionOfError: String) {
//        print("onPaymentError ::: \(descriptionOfError)")
//        let result = ["success" : false,
//                      "message" : descriptionOfError,
//                      "transaction_id": "Not Found"] 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])
//        }
//    }
//
//    func onPaymentSuccess(paymentId: String) {
//        print("onPaymentSuccess ::: \(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])
//        }
//    }
    
  }
