//
//  ExtraWebViewControllerSwift.swift
//  MCPlus
//
//  Created by seo ha on 15/02/2019.
//  Copyright © 2019 KangSH. All rights reserved.
//

import Foundation
import UIKit
import WebKit

class ExtraWebViewController: UIViewController {
    
    @IBOutlet weak var webView:WKWebView!{
        didSet{
            webView.uiDelegate = self
            webView.navigationDelegate = self
            
            webView.configuration.userContentController.add(self, name: "mCarePlus")
            webView.configuration.suppressesIncrementalRendering = false // 데이터를 모두 받아야만 화면이 보여지게 하는 옵션
            
            var scriptContent = "var meta = document.createElement('meta');"
            scriptContent += "meta.name='viewport';"
            scriptContent += "meta.content='width=device-width';"
            scriptContent += "document.getElementsByTagName('head')[0].appendChild(meta);"
            
            webView.evaluateJavaScript(scriptContent, completionHandler: nil)
            webView.evaluateJavaScript("navigator.userAgent") { [weak webView](result, error) in
                if let userAgent = result as? String{
                    webView?.customUserAgent = userAgent.appending("/mCarePlus")
                }
            }
            
            guard let url = URL(string: url ?? "") else {
                return
            }
            
            let request = URLRequest(url: url)
            webView.load(request)
            webView.isUserInteractionEnabled = true
            webView.scrollView.bounces = true
            webView.scrollView.isScrollEnabled = true
            
        }
    }
    @IBOutlet weak var menuBar:UIToolbar!
    
    @IBOutlet weak var backward:UIBarButtonItem!{
        didSet{
            backward.action = #selector(actionBackward(_:))
        }
    }
    
    @IBOutlet weak var forward:UIBarButtonItem!{
        didSet{
            forward.action = #selector(actionForward(_:))
        }
    }
    
    @IBOutlet weak var refresh:UIBarButtonItem!{
        didSet{
            refresh.action = #selector(actionRefresh(_:))
        }
    }
    
    @IBOutlet weak var close:UIBarButtonItem!{
        didSet{
            close.action = #selector(actionClose(_:))
        }
    }
    
    var url:String?
    
    
    
}

extension ExtraWebViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.frame = self.view.frame
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    @objc func actionBackward(_ event:UIEvent){
        print("actionBackward")
        if self.webView.canGoBack{
            self.webView.goBack()
        }
    }
    
    @objc func actionForward(_ event:UIEvent){
        print("actionForward")
        if self.webView.canGoForward{
            self.webView.goForward()
        }
    }
    
    @objc func actionRefresh(_ event:UIEvent){
        print("actionRefresh")
        self.webView.reload()
    }
    
    @objc func actionClose(_ event:UIEvent){
        print("actionClose")
        self.dismiss(animated: true, completion: nil)
    }
    
}

extension ExtraWebViewController:WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler{
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping ((WKNavigationActionPolicy) -> Void)) {
        
        let request = navigationAction.request
        
        guard let url = request.url else {
            return
        }
        
        let absoluteString = url.absoluteString
        
        switch absoluteString {
        //메일
        case let variable where variable.hasPrefix("mailto:"):
            fallthrough
        //전화
        case let variable where variable.hasPrefix("tel:"):
            fallthrough
        //아이튠즈
        case let variable where variable.hasPrefix("https://itunes.apple.com/"):
            fallthrough
        //스토리링크
        case let variable where variable.hasPrefix("storylink://"):
            UIApplication.shared.open(url)
            decisionHandler(.cancel)
        //일반 웹호출
        case let variable where variable.hasPrefix("http://"):
            fallthrough
        case let variable where variable.hasPrefix("https://"):
            decisionHandler(.allow)
        default:
            decisionHandler(.cancel)
        }
        
        
        self.backward.tintColor = webView.canGoBack ? UIColor.white : UIColor.clear
        self.backward.isAccessibilityElement = webView.canGoBack
        
        self.forward.tintColor = webView.canGoForward ? UIColor.white : UIColor.clear
        self.forward.isAccessibilityElement = webView.canGoForward
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        if let urlResponse = navigationResponse.response as? HTTPURLResponse,
            let url = urlResponse.url,
            let allHeaderFields = urlResponse.allHeaderFields as? [String : String] {
            let cookies = HTTPCookie.cookies(withResponseHeaderFields: allHeaderFields, for: url)
            HTTPCookieStorage.shared.setCookies(cookies , for: url, mainDocumentURL: nil)
            decisionHandler(.allow)
        }
    }
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo,
                 completionHandler: @escaping () -> Void) {
        
        self.showAlert("", message, "확인", nil, { (action) in
            completionHandler()
        })
    }
    
    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo,
                 completionHandler: @escaping (Bool) -> Void) {
        
        self.showAlert("", message, "확인", "취소", { (action) in
            completionHandler(true)
        },{ (action) in
            completionHandler(false)
        })
    }
    
    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo,
                 completionHandler: @escaping (String?) -> Void) {
        
        let alertController = UIAlertController(title: "", message: prompt, preferredStyle: .alert)
        alertController.addTextField { (textField) in
            textField.text = defaultText
        }
        alertController.addAction(UIAlertAction(title: "확인", style: .default, handler: { (action) in
            if let text = alertController.textFields?.first?.text {
                completionHandler(text)
            } else {
                completionHandler(defaultText)
            }
        }))
        
        alertController.addAction(UIAlertAction(title: "취소", style: .default, handler: { (action) in
            completionHandler(nil)
        }))
        
        self.present(alertController, animated: true, completion: nil)
    }
    
    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
        let userController = WKUserContentController()
        
        configuration.preferences.javaScriptCanOpenWindowsAutomatically = true
        configuration.userContentController = userController
        
        let newWebView:WKWebView = {
            let webView = WKWebView(frame: webView.frame, configuration: configuration)
            webView.uiDelegate = self
            webView.navigationDelegate = self
            webView.frame.origin.y = 0
            webView.configuration.userContentController.add(self, name: "mCarePlus")
            webView.evaluateJavaScript("navigator.userAgent") { [weak webView](result, error) in
                if let userAgent = result as? String{
                    webView?.customUserAgent = userAgent.appending("/mCarePlus")
                }
            }
            
            return webView
        }()
        
        let button:UIButton = {
            let button = UIButton(type: .system)
            button.isHidden = true
            button.frame = CGRect(x:(webView.frame.size.width) - 30, y:0, width: 30, height: 30)
            button.backgroundColor = UIColor.black
            button.layer.cornerRadius = 15
            button.setTitle("X", for: .normal)
            button.addTapGestureRecognizer(action: deleteSubWebView)
            return button
        }()
        
        webView.addSubview(newWebView)
        webView.addSubview(button)
        
        return newWebView
    }
    
    func deleteSubWebView(){
        for view in webView.subviews{
            view.removeFromSuperview()
        }
    }
    
    func webViewDidClose(_ webView: WKWebView) {
        for view in webView.subviews{
            view.removeFromSuperview()
        }
        webView.removeFromSuperview()
    }
    
    public func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
        // 중복적으로 리로드가 일어나지 않도록 처리 필요.
        webView.reload()
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        
    }
}
