SearchResultViewController.swift 2.74 KB
//
//  SearchResultViewColroller.swift
//  browser
//
//  Created by Artem Talko on 05.10.2023.
//

import UIKit
import WebKit

final class SearchResultViewController: UIViewController {
    let mainView = SearchResultView()
    
    var searchLink: String
    var onCloseButtonTapped: (() -> Void)?
    
    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() {
        urlChecker(searchLink)
        setupAdBlocker()
        addTargets()
    }
    
    override func viewIsAppearing(_ animated: Bool) {
        navigationController?.isNavigationBarHidden = true
    }
}

//MARK: Helper
extension SearchResultViewController {
    private func addTargets() {
        mainView.closeWebViewButton.addTarget(self, action: #selector(closeWebViewTapped(_ :)), for: .touchUpInside)
    }
    
    private func urlChecker(_ url: String) {
        let request = URLRequest(url: URL(string: url) ?? URL(fileURLWithPath: ""))
        mainView.searchResultView.load(request)
    }
}

//MARK: Action
extension SearchResultViewController {
    @objc
    private func closeWebViewTapped(_ sender: UIButton) {
        onCloseButtonTapped?()
    }
}


//MARK: AdBlocker
extension SearchResultViewController {
    private func setupAdBlocker() {
        let userDefaultsAdblockKey = CachingManager.shared.adBlockerState
        if userDefaultsAdblockKey {
            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)
                        }
                    }
                }
            }
        }
    }
}