//
//  PaymentWebViewVC.swift
//  WOKA
//
//  Created by MacBook Pro on 29/07/24.
//

import UIKit
import WebKit

class PaymentWebViewVC: UIViewController,WKNavigationDelegate {

    @IBOutlet weak var webView: WKWebView!
    var url : String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        DispatchQueue.main.async {
            Utilities.startProgressHUD()
        }
        
        if let url {
            let link = URL(string:url)!
            let request = URLRequest(url: link)
            webView.load(request)
        }
        webView.navigationDelegate = self
        //Observer to check the url changes
        webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)

    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: animated)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: animated)
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        Utilities.dismissProgressHUD()
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if let key = change?[NSKeyValueChangeKey.newKey] {
            print("observeValue \(key)") // url value
            if let finalURL = key as? URL {
                let endpoint = finalURL.lastPathComponent
                var domain = String()
                if #available(iOS 16.0, *) {
                    domain = finalURL.host() ?? ""
                } else {
                    domain = finalURL.host ?? ""
                }
                
                if domain == "secure.ccavenue.com" && endpoint.lowercased() == "canceltransaction"{ // failure
                    Timer.scheduledTimer(withTimeInterval: 2.5, repeats: false) { _ in
                        self.navigationController?.popViewController(animated: true)
                    }
                }else if domain == "secure.ccavenue.com" && endpoint.lowercased() == "redirectToMerchant"{ // success
                    // nav to home. & delete my cart
                    CartDataCache.shareInstance.removeAll()
                    Timer.scheduledTimer(withTimeInterval: 2.5, repeats: false) { _ in
                        self.navigationController?.popToRootViewController(animated: true)
                    }
                }
            } else {
                print("urlAny is not a String")
            }
        }
    }
    

}
