//
//  WebView.swift
//  Bill24OnlinePaymentSdk
//
//  Created by MacbookPro on 29/10/23.
//

import Foundation
import UIKit
import Alamofire
import WebKit

public class WebView: UIView , WKNavigationDelegate{
    
    @IBOutlet weak var centerLoading: UIActivityIndicatorView!
    @IBOutlet  var webView: WKWebView!
    private var generateLinkResponse: GenerateLinkResponse?
    var url: String = ""
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        initSubviews()
    }
    
    init(frame: CGRect, url: String) {
        self.url = url
        super.init(frame: frame)
        initSubviews()
    }
    
    private func initSubviews(){
        registerView()
        initWKWebView()
    }
    
    private func registerView() {
        let nib = UINib(nibName: "WebView", bundle: B24PaymentSdkHelper.frameworkBundle())
        
        guard let view = nib.instantiate(withOwner: self, options: nil).first as?
                UIView else {fatalError("Unable to convert nib")}
        
        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        
        addSubview(view)
        print("*** load Web View***")
        self.showLoading()
    }
    
    private func initWKWebView(){
        // Initialize WKWebView
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: bounds, configuration: webConfiguration)
        webView.navigationDelegate = self
        addSubview(webView)
        // Load initial URL
        loadURL(urlString: url)
    }
    
    private func loadURL(urlString: String) {
        if let url = URL(string: urlString) {
            let request = URLRequest(url: url)
            webView.load(request)
        }
    }
    
    // Handle page loading events here if needed
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // Web page has finished loading
        print("Page Loaded")
        hideLoading()
    }
    
    public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        // Handle page loading failure here
        print("Failed to load WebView: \(error.localizedDescription)")
        hideLoading()
        // You can show an error message to the user here if needed
    }
    
    public func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        // Handle provisional navigation failure here
        print("Failed to load provisional navigation: \(error.localizedDescription)")
        hideLoading()
        // You can show an error message to the user here if needed
    }
    
    private func showLoading(){
        centerLoading.startAnimating()
        centerLoading.isHidden = false
    }
    
    private func hideLoading(){
        centerLoading.stopAnimating()
        centerLoading.isHidden = true
    }
}

