SearchResultViewController.swift 2.44 KB
//
//  SearchResultViewColroller.swift
//  browser
//
//  Created by Artem Talko on 05.10.2023.
//
//MARK: Checked

import UIKit
import WebKit

final class SearchResultViewController: UIViewController {
    let mainView = SearchResultView()
    var searchLink: String
    
    init(searchLink: String) {
        self.searchLink = searchLink
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func loadView() {
        view = mainView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initViewController()
    }
    
    private func initViewController() {
        view.backgroundColor = ColorConstants.lightGray
        
        urlChecker(searchLink)
        setupAdBlocker()
    }
  
    override func viewIsAppearing(_ animated: Bool) {
        navigationController?.isNavigationBarHidden = true
    }
}

extension SearchResultViewController {
    private func urlChecker(_ url: String) {
            let request = URLRequest(url: URL(string: url) ?? URL(fileURLWithPath: ""))
            mainView.searchResultView.load(request)
    }
}


//MARK: AdBlocker
extension SearchResultViewController {
    private func setupAdBlocker() {
        let userDefaultsValue = CachingManager.shared.isAdBlocking
        if userDefaultsValue {
            WKContentRuleListStore.default().getAvailableContentRuleListIdentifiers { res in
                    if let url = Bundle.main.url(forResource: "blockerList", withExtension: "json"),
                       let str = try? String(contentsOf: url) {
                        WKContentRuleListStore.default().compileContentRuleList(forIdentifier: "blockerList", encodedContentRuleList: str) { list, error in
                            if let list {
                                self.mainView.searchResultView.configuration.userContentController.add(list)
                            }
                        }
                    }
            }
        } else {
            WKContentRuleListStore.default().getAvailableContentRuleListIdentifiers { res in
                if res != nil {
                    WKContentRuleListStore.default().removeContentRuleList(forIdentifier: "blockerList") { error in
                        if let error {
                            print(error)
                        }
                    }
                }
            }
        }
    }
}