//
//  OptOutVC.swift
//  SimpleNoADSDKPods
//
//  Created by Abdul Rafay Mohd on 20/04/21.
//

import UIKit
import WebKit
import NielsenAppApi

class OptOutVC: UIViewController, NielsenAppApiDelegate, WKNavigationDelegate {
    
    var webView: WKWebView!
    var nielsenApi: NielsenAppApi!
    var optOutURL: String!
    
    //Initializing and loading the webview
    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if let url = URL(string: optOutURL) {
            webView.load(URLRequest(url: url))
            webView.allowsBackForwardNavigationGestures = true
        }
        
        //Initializing the Nielsen SDK
//        if let appApi = self.nielsenApi {
//            //Getting the optPut URL from SDK.
//            if let url = URL(string: appApi.optOutURL) {
//                
//                //Loading the URL in webview
//                webView.load(URLRequest(url: url))
//                
//                //Allowing webview to do forward and backward navigation.
//                webView.allowsBackForwardNavigationGestures = true
//            }
//        }
    }
    
    //Handling the navigation of Webview
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        
        //If the URL has "nielsen" in it, then user has selected "OptIn/OptOut".
        if let url = navigationAction.request.url?.absoluteString, url.hasPrefix("nielsen") {
            
            //Updating the SDK based on user selection.
            nielsenApi?.userOptOut(url)
            decisionHandler(.cancel)
            
        } else {
            if navigationAction.navigationType == .linkActivated {
                
                //If the url contains "#" then allows to navigate.
                if let url = navigationAction.request.url?.absoluteString, url.hasSuffix("#") {
                    decisionHandler(.allow)
                } else {
                    decisionHandler(.cancel)
                    webView.load(navigationAction.request)
                }
            } else {
                decisionHandler(.allow)
            }
        }
        
    }
    
}

