//
//  ForEmbedViewController.swift
//  AppDemoComercio
//
//  Created by Desarrollo on 28/08/23.
//

import UIKit
import IzipayPayButtonSDK
import RLTMXProfiling
import RLTMXProfilingConnections
import VisaSensoryBranding
import MastercardSonic

protocol ForEmbedVCDelegate {
    
    func passResponseToOrigin(_ paymentResult: PaymentResult)
    
}

//Este view controller es una replica del MainViewController, ajustado para ser usado en el modo embebido
class ForEmbedVC: UIViewController {

    private let sonicManager: MCSonicController = MCSonicController()
    private var profile : RLTMXProfiling? = RLTMXProfiling.sharedInstance()
    
    var configIzipay : ConfigPaymentIzipay?
    var transactionId : String?
    var delegate : ForEmbedVCDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.showIzipayPaymentEmbedded()
    }
    
    @IBOutlet weak var viewContainer: UIView!
    
    
    /**
     * Integración con iOS - Modos de visualización
     * https://developers.izipay.pe/ios-core/integration-with-ios/#modos-de-visualizaci%C3%B3n
     */
    func showIzipayPaymentEmbedded(){
        let s = UIStoryboard(name: "IziPayment", bundle: Bundle(for: PaymentFormViewController.self))
        let vc = s.instantiateViewController(withIdentifier: "PaymentFormView") as! PaymentFormViewController
        vc.delegate = self
        vc.configPayment = self.configIzipay
        addChild(vc)
        vc.view.frame = viewContainer.bounds
        viewContainer.addSubview(vc.view)
        vc.didMove(toParent: self)
    }
    
    
    @IBAction func onTapBack(_ sender: Any) {
        var resultBack = PaymentResult()
        resultBack.code = "CERRADO X COMERCIO"
        resultBack.message = "El SDK(en modo embebido) fue cerrado por la app del comercio, esta respuesta viene de la app del comercio."
        //consultar al api de consulta de transacciones
        delegate?.passResponseToOrigin(resultBack)
        self.dismiss(animated: false)
    }
}

extension ForEmbedVC : IzipayPaymentDelegate {
    
    func executeSensoryBrandVisa(view: UIView) {
        if let visaview = view as? SensoryBranding {
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                visaview.animate()
            }
        }
    }
    
    func executeSensoryBrandMastercard(view: UIView, params: MastercardSonicParams) {
        let merchant = MCSonicMerchant(merchantName: params.name, countryCode: params.country,
                                       city: nil, merchantCategoryCodes: [params.mcc], merchantId: nil)
        
        if let mastercardview = view as? MCSonicView, let safeMerchant = merchant {
            self.sonicManager.prepare(with: .soundAndAnimation, sonicCue: params.sonicCue,
                                      sonicEnvironment: .sandbox, merchant: safeMerchant) { status in
                
                if status == .success {
                    self.sonicManager.play(with: mastercardview) { MCSonicStatus in
                        print(MCSonicStatus)
                    }
                }
            }
            
        }
    }
    
    
    func executeProfiling(_ params: IzipayPayButtonSDK.ScoringParams) {
        let profilingConnections : RLTMXProfilingConnections  = RLTMXProfilingConnections.init()
        profilingConnections.connectionTimeout    = TimeInterval(params.timeout);
        profilingConnections.connectionRetryCount = Int32(params.intents);
        profile = RLTMXProfiling.sharedInstance()
        profile?.configure(configData:[
                            RLTMXOrgID              : params.userOrg ?? "",
                            RLTMXFingerprintServer  : params.defaultServer ?? "",
                            RLTMXProfileTimeout     : profilingConnections.connectionTimeout,
                            RLTMXProfilingConnectionsInstance: profilingConnections,
        ])
        self.doProfileRequest(forUser: params.userScoring ?? "", with: params.randomFp ?? "")
    }

    private func doProfileRequest(forUser userScoring : String, with id : String) {
        let customAttributes : [String : String] = [RLTMXSessionID: "\(userScoring)\(id)"]
        
        if let safeProfile = self.profile {
            let _: RLTMXProfileHandle =
            safeProfile.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)!
                _ = results.value(forKey: RLTMXSessionID) as! String
                print("Estado evaluacion cybersource: \(status)")
                if status == RLTMXStatusCode.ok {
                    // .RLTMXStatusCodeOk en lugar de .ok en versiones antiguas 
                    // No errors, profiling succeeded!
                    print("Cybersource profiling OK")
                } else {
                    print("Cybersource profiling FAILURE")
                    //TODO: Enviar info al api event si es posible
                }
            })
            
        }
    }
    
    func getPaymentResult(_ paymentResult: PaymentResult) {
        //Lectura de respuesta del SDK
        
        self.dismiss(animated: false) { [weak self] in
            self?.delegate?.passResponseToOrigin(paymentResult)
        }
    }
    
    
    
}
