import UIKit
import WebKit
import PassKit

protocol NavigatorDelegate {
   func onClosed()
}

class NavigatorController: MyUIViewController, WKNavigationDelegate{
    

    
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    @IBOutlet weak var view_container: UIView!
    @IBOutlet weak var activity_indicator: UIActivityIndicatorView!
    
    var delegate: NavigatorDelegate?
    
    
    var navigatorTitle:String?
    var link:String?
    var webView: WKWebView?

    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        activity_indicator.color = Colors.primaryColor
        
        setupNavigationBar()
        setupNavBarButtons()
        setupNavBarTitles()
       
        if let ti = navigatorTitle{
            topBarTitle.text = ti.localized
        }
    
        
        if let sess = Session.getInstance(), let user = sess.user{
            setupWebView()
        }

        
    }
    
    
    
    func setupNavigationBar() {
        self.navigationBar.isTranslucent = false
        self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        self.navigationBar.shadowImage = UIImage()
        self.navigationBar.tintColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
        
    }
    
    func setupNavBarTitles() {
           
           let rect = CGRect(x: 0, y: 0, width: view.frame.width - 32, height: view.frame.height)
           topBarTitle.frame = rect
           topBarTitle.textColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
           topBarTitle.font = UIFont(name: AppConfig.Design.Fonts.regular, size: 17)
           topBarTitle.leftTextInset = 5
           
           topBarTitle.text = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
           
           navigationBarItem.titleView = topBarTitle

       }
    
    let topBarTitle: EdgeLabel = {

         let titleLabel = EdgeLabel()

         let appname = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String ?? "Home".localized

         titleLabel.text = appname

        titleLabel.textColor = Colors.primaryColor

         titleLabel.font = UIFont.systemFont(ofSize: 20)

         return titleLabel

     }()
    
    
    func setupNavBarButtons() {
           
           //arrow back icon
           var icon: UIImage? = nil
            icon = UIImage.init(icon: .googleMaterialDesign(.close), size: CGSize(width: 30, height: 30), textColor: Colors.darkColor)
           

           let _color = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.primaryColor)
           let customBackButtonItem = UIBarButtonItem(image: icon!, style: .plain, target: self, action: #selector(onBackHandler))
           customBackButtonItem.setIcon(icon: .ionicons(.iosArrowBack), iconSize: 25, color: _color)
           
           
           navigationBarItem.leftBarButtonItems = []
           navigationBarItem.rightBarButtonItems = []
           
           if(config.backHome){
               navigationBarItem.leftBarButtonItems?.append(customBackButtonItem)
           }
           
           
       }

    
    private func setupWebView(){
        
        
        //init webview
        self.webView = WKWebView()
        self.webView?.frame = self.view_container.frame
        if let _webView  = self.webView {
            
            self.view_container.addSubview(_webView)
            
            self.view_container.addConstraintsWithFormat(format: "H:|[v0]|", views: _webView)
            self.view_container.addConstraintsWithFormat(format: "V:|[v0]|", views: _webView)
            
            _webView.navigationDelegate = self
            _webView.translatesAutoresizingMaskIntoConstraints = false
            
            _webView.isHidden = true
            
        }
        
        //start loding
        
        if let _webView = self.webView{
                   
           self.activity_indicator.isHidden = false
            self.activity_indicator.startAnimating()
            
            let url = URL(string: link!)!
            _webView.load(URLRequest(url: url))
                            
            _webView.isHidden = false
            _webView.allowsBackForwardNavigationGestures = true
                              
            self.view.layoutIfNeeded()
                   
        }
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        
        self.activity_indicator.isHidden = false
        navigationBarItem.rightBarButtonItems = []
        
    }
    
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
                                 
           
           if let response = navigationResponse.response as? HTTPURLResponse {
               if response.statusCode != 200 {
                   self.webView?.isHidden = false
                   let message = "Error \(response.statusCode)"
                   self.showAlertError(title: "Error",content: ["":message] ,msgBnt: "OK")
                   decisionHandler(.allow)
                   return
               }
           }
           
           decisionHandler(.allow)
       }
    
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
          if let url = navigationAction.request.url?.absoluteString {
            Utils.printDebug("BusinessManager: \(url)")
            checkCallbackURL(url: url)
          }
          
          decisionHandler(.allow)
      }
    
    
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
        self.activity_indicator.isHidden = true


    }
    
    var links:[String] = []
    
    func checkCallbackURL(url: String) -> Bool {
        
        let result  = handleApplePay(url: url)
        
        if(result){
            return false
        }
       
        let requestURLString = url
        if requestURLString.hasPrefix(AppConfig.Api.base_url) && requestURLString != link {
            links.append(requestURLString)
            return false;
        }
        return true
    }
   
    var invoiceId: String? = nil
    
    func handleApplePay(url: String) -> Bool{
        
        Utils.printDebug("\(url)")
        
        let requestURLString = url
        
       if  requestURLString.contains("payment/process_payment") && requestURLString.regMatchGroup(regex: "mp=10012").count > 0{
        
        
        guard let invoiceid = requestURLString.getIdFromUrl(pattern: "invoiceid") else {
            self.onBackHandler()
            return false
        }
        
       
       
        let params = [
            "invoiceId": invoiceid
        ]
        
        MyProgress.show(parent: self.view)
        
        let api = SimpleRequestApi()
        
    
        api.run(url: AppConfig.Api.base_url_api+"/"+Constances.Api.API_VERSION+"/payment/getInvoiceForApplePay", parameters: params) { parser in
            
            MyProgress.dismiss()
            
          
            if parser?.success == 1, let result = parser?.result{
               
                self.invoiceId = invoiceid
               
                let amount_to_pay = result["details_subtotal"].doubleValue
                let currency = result["currency"].stringValue
            
                Utils.printDebug("\(amount_to_pay)")
              
                //proccess the payment using apple pay
                var paymentRequest: PKPaymentRequest = {
                        let request = PKPaymentRequest()
                    request.merchantIdentifier = AppConfig.ApplePayConfig.merchantIdentifier
                    request.supportedNetworks = AppConfig.ApplePayConfig.supportedNetworks
                        if #available(iOS 11.0, *) {
                           // request.supportedCountries = AppConfig.ApplePayConfig.supportedCountries
                        } else {
                            // Fallback on earlier versions
                            self.onBackHandler()
                        }
                        request.merchantCapabilities = .capability3DS
                        request.countryCode = AppConfig.ApplePayConfig.codeCountry
                        request.currencyCode = currency
                    request.paymentSummaryItems = [PKPaymentSummaryItem(label: AppConfig.APP_NAME, amount: NSDecimalNumber(value: amount_to_pay))]
                        return request
                    }()
                
                
                if let controller = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest) {
                    controller.delegate = self
                    self.present(controller, animated: true, completion: nil)
                }
                
                
            }
        }
        
    
        }
        

        
        return true;
    }
    
    var paid: Bool = false
    
    
    @objc func onBackHandler()  {
        
        
    
        if let controller = self.navigationController{
                       //controller.navigationBar.isHidden = true
                       controller.popViewController(animated: true)
                       ////controller.navigationBar.isHidden = false
                   }else{
                       self.dismiss(animated: true)
                   }
        
        
        if let del = delegate{
            del.onClosed()
        }
        
    }
    
    
}




extension NavigatorController: PKPaymentAuthorizationViewControllerDelegate {
 
    
    @available(iOS 11.0, *)
    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment payment: PKPayment, handler completion: @escaping (PKPaymentAuthorizationResult) -> Void) {
        
        let token = payment.token
        let transactionIdentifier = token.transactionIdentifier
        let paymentMethod = token.paymentMethod.displayName
        
        MyProgress.show(parent: self.view)
        
        guard let ivid = self.invoiceId else {
            self.showAlertError(title: "Payment error".localized, content: ["" : "Invoice ID is missed!".localized], msgBnt: "OK".localized)
            return
        }
        
        let api = SimpleRequestApi()
        
        var parameters = [
            "invoiceId": ivid,
            "transactionId": transactionIdentifier,
            "paymentMethod": "ApplePay:\(paymentMethod!)"
        ]
        
        
        api.run(url: AppConfig.Api.base_url_api+"/"+Constances.Api.API_VERSION+"/payment/updateInvoiceApplePay", parameters: parameters) { parser in
            
            MyProgress.dismiss()
            
            if parser?.success == 1{
                self.paid = true
                completion(PKPaymentAuthorizationResult(status: .success, errors: nil))
            }else{
                completion(PKPaymentAuthorizationResult(status: .failure, errors: nil))
                self.showAlertError(title: "Payment error".localized, content: ["" : "occurred error during making the payment".localized], msgBnt: "OK".localized)
            }
            
        }
        
    }
 
    func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
        
        MyProgress.dismiss()
        controller.dismiss(animated: true, completion: nil)
    
        
        if self.paid == true{
            
            self.link = AppConfig.Api.base_url+"/payment/payment_success"
            if let _webview = self.webView{
                
                let url = URL(string: link!)!
                _webview.load(URLRequest(url: url))
                
            }
            
        }else{
            
            self.link = AppConfig.Api.base_url+"/payment/payment_error"
            if let _webview = self.webView{
                
                let url = URL(string: link!)!
                _webview.load(URLRequest(url: url))
                
            }
            
        }
    
    }
    

    
    
    
    func updateInvoice(invoiceid: String,transactionId: String) {
        
     
    }

}

