//
//  WKWebViewController.swift
//  HybridWebPlayerSwift
//
//  Created by Mike Petrov on 03.04.2020.
//  Copyright © 2020 alex kuznetsov. All rights reserved.
//

import Foundation
import UIKit
import NielsenAppApi
import WebKit

@objc(WKWebViewController)
class WKWebViewController: UIViewController {
    
    @IBOutlet weak var webContainerView: UIView!
    weak var webView: WKWebView?
    
    let jsFunctionNativeMessage = "nativeMsg"

    var jsAppSDK: NielsenAppSDKJSHandler?
    var apiType: String?
    var urlString: String?

    func addWebView() {
        let configuration = WKWebViewConfiguration()
        configuration.allowsInlineMediaPlayback = true

        let webView = WKWebView(frame: .zero, configuration: configuration)
        webView.translatesAutoresizingMaskIntoConstraints = false
        webContainerView.addSubview(webView)

        self.webView = webView
        webContainerView.addConstraints(NSLayoutConstraint.constraints(
            withVisualFormat: "V:|-0-[webView]-0-|",
            options: .directionLeadingToTrailing,
            metrics: nil,
            views: ["webView":webView]))
        webContainerView.addConstraints(NSLayoutConstraint.constraints(
            withVisualFormat: "H:|-0-[webView]-0-|",
            options: .directionLeadingToTrailing,
            metrics: nil,
            views: ["webView":webView]))
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        if self.responds(to: #selector(setter: edgesForExtendedLayout)) {
            self.edgesForExtendedLayout = .init(rawValue: 0)
        }
        
        addWebView()
        
        if let sdk = NielsenAppSDKJSHandler(apiType: self.apiType) {
            self.jsAppSDK = sdk
            if let webView = self.webView, let urlString = self.urlString {
                webView.configuration.userContentController.add(sdk, name: jsFunctionNativeMessage)
                if let url = URL(string: urlString) {
                    webView.load(URLRequest(url: url))
                }
            }
        }
    }
    
    deinit {
        if let webView = self.webView {
            webView.configuration.userContentController.removeScriptMessageHandler(forName: jsFunctionNativeMessage)
        }
        self.jsAppSDK = nil
        if let webView = self.webView {
            webView.removeFromSuperview()
        }
        self.webView = nil
    }
    
    @IBAction func onReloadBtn(_ sender: AnyObject?) {
        if let webView = self.webView {
            webView.configuration.userContentController.removeScriptMessageHandler(forName: jsFunctionNativeMessage)
            if let url = URL(string: "about:blank") {
                webView.load(URLRequest(url: url))
            }
        }
        
        DispatchQueue.main.async(execute: { () -> Void in
            if let sdk = NielsenAppSDKJSHandler(apiType: self.apiType) {
                self.jsAppSDK = sdk
                if let webView = self.webView, let urlString = self.urlString {
                    webView.configuration.userContentController.add(sdk, name: self.jsFunctionNativeMessage)
                    if let url = URL(string: urlString) {
                        webView.load(URLRequest(url: url))
                    }
                }
            }
        })
    }
}

