import UIKit
import WebKit
import PKHUD

class DkbmController: UIViewController, WKScriptMessageHandler {

    private var webView: WKWebView!
    private var captchaAdded = false
    
    var onDone: ((String) -> Void)?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let config = WKWebViewConfiguration()
        if let jsPath = Bundle.main.path(forResource: "dkbm", ofType: "js") {
            let js = try? String(contentsOfFile: jsPath)
            let contentController = WKUserContentController()
            let script = WKUserScript(source: js!, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
            contentController.addUserScript(script)
            contentController.add(self, name: "dkbmHandler")
            config.userContentController = contentController
        }
        
        self.webView = WKWebView(frame: .zero, configuration: config)
        self.webView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(self.webView)
        NSLayoutConstraint.activate([
            self.webView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            self.webView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
            self.webView.topAnchor.constraint(equalTo: self.view.topAnchor),
            self.webView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
        ])
        
        //self.webView.isHidden = true
        //HUD.show(.progress)
        
        let url = URL(string: "https://dkbm-web.autoins.ru/dkbm-web-1.0/policyInfo.htm")!
        let request = URLRequest(url: url)
        self.webView.load(request)
    }
    
    // MARK: - WKScriptMessageHandler
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        guard let msg = message.body as? [String:String] else { return }
        print(msg)
        
        if let event = msg["event"] {
            if event == "show-challenge" {
                if self.captchaAdded {
                    HUD.hide()
                    self.webView.isHidden = false
                }
            } else if event == "show-checkbox" {
                self.captchaAdded = true
            }
        } else if let token = msg["token"] {
            self.onDone?(token)
        }
    }
}
