//
//  LLQ_WebView.swift
//  PrivateBrowser
//
//  Created by MAC on 2022/6/14.
//

import UIKit
import WebKit
import RxSwift
class LLQ_WebView : WKWebView {
    private var disposeBg = DisposeBag()
    var viewModel: LLQ_HomeSinglePageViewModel
    init(frame: CGRect, configuration: WKWebViewConfiguration, singleVm: LLQ_HomeSinglePageViewModel) {
        self.viewModel = singleVm
        configuration.allowsInlineMediaPlayback = true
        super.init(frame: frame, configuration: configuration)
        self.navigationDelegate = self
        self.uiDelegate = self
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func load(_ request: URLRequest) -> WKNavigation? {
        // update url
        if let url = request.url?.absoluteString {
            self.viewModel.startLoadUrlStringStream.accept(url)
        }
        return super.load(request)
    }
}

extension LLQ_WebView: WKNavigationDelegate, WKUIDelegate {
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        let url = navigationAction.request.url
        let urlString = url?.absoluteString ?? ""
        if urlString.isMatchString(pattern: "\\/\\/itunes\\.apple\\.com\\/") || urlString.isMatchString(pattern: "apps\\.apple\\.com") {
            UIApplication.shared.openURL(URL(string: urlString)!)
            decisionHandler(.cancel)
            return
        }
        if url?.scheme == "tel", let url = url as NSURL?, let phoneNumber = url.resourceSpecifier?.removingPercentEncoding {
            let alertController = UIAlertController.init(title: phoneNumber, message: nil, preferredStyle: .alert)
            let _ = alertController.addAction(title: "Call", style: .default) { action in
                UIApplication.shared.openURL(url as URL)
            }
            let _ = alertController.addAction(title: "Canel", style: .cancel) { _ in
                
            }
            LLQ_RootViewController.now.present(alertController, animated: true, completion: nil)
            return
        }
        if navigationAction.targetFrame == nil {
            if urlString.hasSuffix(".apk") {
                decisionHandler(.cancel)
                return
            }
            // start
            self.viewModel.openNewWebStream.accept(urlString)
        }
        decisionHandler(.allow)
    }
    
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        decisionHandler(.allow)
    }
    
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        NSLog("---  didFail navigation \(error.localizedDescription)")
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        if let urlString = webView.url?.absoluteString {
            self.viewModel.textFieldUpdateTextStream.accept(urlString)
        }
    }
}
