BrowserHomeViewController.swift 16.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433
//
//  ViewController.swift
//  browser
//
//  Created by Artem Talko on 25.09.2023.
//
//MARK: Checked

import UIKit
import SnapKit
import WebKit
import Combine
import Realm

final class BrowserHomeViewController: UIViewController {
    let mainView = BrowserHomeView()
    
    private let searchingViewController: SearchingViewController
    private let searchResultViewController: SearchResultViewController
    private let tabsViewController: TabsViewController
    
    private var subscriptions: Set<AnyCancellable>
    private var searchRequestURL: String
    private let images = StringConstants.browserHomeVCImages
    private var currentTabId: Int?
    
    private var url: String? {
        didSet {
            searchRequestURL = url ?? String()
            openSearchResult()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = ColorConstants.lightGray
        
        initViewController()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        keyboardObserver()
    }
    
    private func initViewController() {
        setupCollectionView()
        addTargets()
        setupSearchBarComponentsAction()
        setupSearchingViewController()
        progressObserver()
    }
    
    override func viewIsAppearing(_ animated: Bool) {
        navigationController?.isNavigationBarHidden = true
    }
    
    override func loadView() {
        view = mainView
    }
    
    init(url: String?, currentTabId: Int?) {
        searchResultViewController = SearchResultViewController(searchLink: String())
        searchingViewController = SearchingViewController(dataForReq: [])
        tabsViewController = TabsViewController()
        
        subscriptions = []
        searchRequestURL = URLConstants.googleURL
        
        super.init(nibName: nil, bundle: nil)
        self.url = url
        self.currentTabId = currentTabId
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
}


//MARK: CollectionView Setup
extension BrowserHomeViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        images.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TabCollectionViewCell.cellID, for: indexPath) as? TabCollectionViewCell else {
            return TabCollectionViewCell()
        }
        let finalCell = setupCellForCollectionView(cell, indexPath)
        
        return finalCell
    }
    
    func setupCellForCollectionView(_ cell: TabCollectionViewCell, _ indexPath: IndexPath) -> TabCollectionViewCell {
        let imageName = images[indexPath.item]
        cell.tabCellImage.image = UIImage(named: imageName)
        cell.tabCellLabel.text = imageName
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 72.sizeW, height: 104.sizeH)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        searchRequestURL = StringConstants.browserHomeVCurl[indexPath.row]
        openSearchResult()
    }
}


//MARK: - Keyboard extention
extension BrowserHomeViewController {
    private func keyboardObserver() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear), name: UIResponder.keyboardWillHideNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    }
}


//MARK: - Action
extension BrowserHomeViewController {
    @objc
    private func searchBarTextChanged() {
        if let text = mainView.searchBarContainer.searchBarView.searchTextFieldView.text {
            searchRequestURL = text
            mainView.searchBarContainer.searchBarView.cleanTextFieldButton.isHidden = false
            if searchRequestURL.isEmpty {
                searchResultAction()
            } else {
                Task {
                    await searchAndReloadTableView()
                }
            }
        }
    }
    
    @objc
    private func searchResultAction() {
        mainView.searchBarContainer.searchBarView.searchTextFieldView.text = nil
        mainView.searchBarContainer.searchBarView.cleanTextFieldButton.isHidden = true
        
        removeChildViewController()
    }
    
    @objc
    private func keyboardWillShow(_ notification: Notification) {
        guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return
        }
        let keyboardHeight = keyboardFrame.height
        self.mainView.animateSearchBar(keyboardHeight)
    }
    
    @objc
    private func keyboardWillDisappear() {
        mainView.animateSearchBarDismiss()
    }
    
    @objc
    private func settingButtonTapped(_ sender: UIButton) {
        let settingViewController = SettingViewController()
        openAdditionViewController(settingViewController)
    }
    
    @objc
    private func removeAdButtonTapped(_ sender: UIButton) {
        let removeAdViewController = RemoveAdvertViewController()
        openAdditionViewController(removeAdViewController)
    }
    
    @objc
    private func removeSearchingViewController(_ sender: UIButton) {
        searchResultAction()
    }
}


//MARK: - Helpers
extension BrowserHomeViewController {
    private func didTabButtonTapped(type: ToolbarElementType) {
        switch type {
        case .history:
            let historyViewController = HistoryViewController()
            present(historyViewController, animated: true, completion: nil)
            break
        case .tabs:
            tabsButtonHandler()
            break
        case .back:
            searchResultViewController.mainView.searchResultView.goBack()
            break
        case .forward:
            searchResultViewController.mainView.searchResultView.goForward()
            break
        case .share:
            let items = [URL(string: searchRequestURL)]
            let shareView = UIActivityViewController(activityItems: items as [Any], applicationActivities: nil)
            present(shareView, animated: true)
            break
        }
    }
    
    private func searchAndReloadTableView() async {
        let sitesFromSearch: [String] = await BrowserSearchService().searchSuggest(searchRequestURL)
        if !sitesFromSearch.isEmpty {
            searchingViewController.searchRequestData = sitesFromSearch
        }
        addingSearchingViewController(searchingViewController)
    }
    
    private func setupCollectionView() {
        mainView.frequentlyVisitedCollectionView.dataSource = self
        mainView.frequentlyVisitedCollectionView.delegate = self
        mainView.frequentlyVisitedCollectionView.register(TabCollectionViewCell.self, forCellWithReuseIdentifier: TabCollectionViewCell.cellID)
    }
    
    private func addTargets() {
        mainView.settingButton.addTarget(self, action:  #selector(settingButtonTapped(_ :)), for: .touchUpInside)
        mainView.removeAddButton.addTarget(self, action: #selector(removeAdButtonTapped(_ :)), for: .touchUpInside)
        mainView.searchBarContainer.searchBarView.searchTextFieldView.addTarget(self, action: #selector(searchBarTextChanged), for: .editingChanged)
        searchingViewController.mainView.searchingButton.addTarget(self, action: #selector(removeSearchingViewController(_ :)), for: .touchUpInside)
        addToolbarTargets()
    }
    
    private func addToolbarTargets() {
        mainView.toolbarView.action = didTabButtonTapped
    }
    
    private func openAdditionViewController(_ viewController: UIViewController) {
        viewController.modalPresentationStyle = .fullScreen
        present(viewController, animated: true, completion: nil)
    }
    
    private func setupSearchingViewController() {
        searchingViewController.searchCell = { [self] cell in
            guard let cell = cell as? SearchingTableViewCell else {
                return
            }
            searchRequestURL = "https://www.google.com/search?q=" + (cell.searchLabel.text ?? "")
            openSearchResult()
            mainView.searchBarContainer.searchBarView.searchTextFieldView.endEditing(true)
        }
    }
    
    private func openSearchResult() {
        let finalSearchRequest = searchRequestURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        searchResultViewController.searchLink = finalSearchRequest ?? ""
        if let localUrl = URL(string: finalSearchRequest ?? "") {
            let request = URLRequest(url: localUrl)
            searchResultViewController.mainView.searchResultView.load(request)
        }
        addingSearchingViewController(searchResultViewController)
    }
    
    private func tabsButtonHandler() {
        if currentTabId == nil {
            addNewTab()
            navigationController?.popViewController(animated: true)
        } else {
            updateCurrentTab()
        }
    }
    
    private func addNewTab() {
        if let childViewController = self.children.first as? SearchResultViewController {
            guard let siteTitle = childViewController.mainView.searchResultView.title else {
                return
            }
            guard let siteUrl = childViewController.mainView.searchResultView.url else {
                return
            }
            let finalUrl = siteUrl.absoluteString
            let lastVisit = DateManager.shared.currentDate
            let wkWVForSnapshot = childViewController.mainView.searchResultView
            
            SnapshotService.shared.makeWKWebViewSnapshot(wkWVForSnapshot) { snapshotForDB in
                TabManager.shared.saveTab(tabTitle: siteTitle, snapshotImage: snapshotForDB, tabUrl: finalUrl)
            }
            HistoryDBManager.shared.saveToHistory(siteTitle: siteTitle, siteUrl: finalUrl, lastVisit: lastVisit)
        } else {
            let homeViewSnapshot = SnapshotService.shared.makeSnapshot(mainView)
            TabManager.shared.saveTab(tabTitle: "Start Page", snapshotImage: homeViewSnapshot, tabUrl: "homeUrl")
            currentTabId = tabsViewController.getCellIndex().row
        }
    }
    
    private func updateCurrentTab() {
        let allTabs = TabManager.shared.getAllTabs()
        let chosenTab = allTabs[self.currentTabId ?? Int()]
        let gottedCellId = chosenTab.tabId
        let imageForUpdatedTab = SnapshotService.shared.makeSnapshot(self.mainView)
        if let childViewController = self.children.first as? SearchResultViewController {
            guard let siteTitle = childViewController.mainView.searchResultView.title else {
                return
            }
            guard let siteUrl = childViewController.mainView.searchResultView.url?.absoluteString else {
                return
            }
            let lastDate = DateManager.shared.currentDate
            
            TabManager.shared.updateTab(tabId: gottedCellId, newTabTitle: siteTitle, newSnapshotImage: imageForUpdatedTab, newTabUrl: siteUrl) { result in
                self.navigationController?.popViewController(animated: true)
            }
            HistoryDBManager.shared.saveToHistory(siteTitle: siteTitle, siteUrl: siteUrl, lastVisit: lastDate)
        } else {
            TabManager.shared.updateTab(tabId: gottedCellId, newTabTitle: "Start Page", newSnapshotImage: imageForUpdatedTab, newTabUrl: "homeUrl") { result in
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
}


//MARK: - ChildVC actions
extension BrowserHomeViewController {
    private func addingSearchingViewController(_ childViewController: UIViewController) {
        if self.children.isEmpty {
            addNewChildViewController(childViewController)
        } else {
            removeChildViewController()
            addNewChildViewController(childViewController)
        }
    }
    
    private func addNewChildViewController(_ child: UIViewController) {
        mainView.addSearchView(child.view)
        child.didMove(toParent: self)
        
        addChild(child)
    }
    
    private func removeChildViewController() {
        if let childViewController = self.children.first as? SearchingViewController {
            childViewController.view.removeFromSuperview()
            childViewController.willMove(toParent: nil)
            childViewController.removeFromParent()
        }
        if let childViewController = self.children.first as? SearchResultViewController {
            childViewController.view.removeFromSuperview()
            childViewController.willMove(toParent: nil)
            childViewController.removeFromParent()
        }
    }
}


//MARK: - SearchBar extention
extension BrowserHomeViewController: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        mainView.searchBarContainer.searchBarView.searchTextFieldView.text = nil
        mainView.searchBarContainer.searchBarView.searchTextFieldView.textColor = .black
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        
        searchRequestURL = "https://www.google.com/search?q=" + (textField.text ?? "")
        openSearchResult()
        
        return true
    }
    
    func setupSearchBarComponentsAction() {
        mainView.searchBarContainer.searchBarView.searchTextFieldView.autocorrectionType = .no
        mainView.searchBarContainer.searchBarView.searchTextFieldView.delegate = self
        mainView.searchBarContainer.searchBarView.cleanTextFieldButton.addTarget(self, action: #selector(searchResultAction), for: .touchUpInside)
        buttonObserver()
    }
}


//MARK: - WebView extention
extension BrowserHomeViewController {
    private func buttonObserver() {
        searchResultViewController.mainView.searchResultView
            .publisher(for: \.canGoBack)
            .sink { [weak self] canGoBack in
                self?.mainView.toolbarView.backBarButtonItem.isEnabled = canGoBack
            }
            .store(in: &subscriptions)
        
        searchResultViewController.mainView.searchResultView
            .publisher(for: \.canGoForward)
            .sink { [weak self] canGoForward in
                self?.mainView.toolbarView.forwardBarButtonItem.isEnabled = canGoForward
            }
            .store(in: &subscriptions)
        
        searchResultViewController.mainView.searchResultView
            .publisher(for: \.isLoading)
            .sink { [weak self] isLoading in
                guard let self = self else { return }
                if let url = self.searchResultViewController.mainView.searchResultView.url {
                    self.searchRequestURL = url.absoluteString
                }
            }
            .store(in: &subscriptions)
    }
    
    private func progressObserver() {
        searchResultViewController.mainView.searchResultView
            .publisher(for: \.estimatedProgress)
            .sink { [weak self] progress in
                guard let self = self else { return }
                self.mainView.searchBarContainer.searchBarView.progressBar.progress = Float(progress)
                if progress == 1 {
                    self.mainView.searchBarContainer.searchBarView.progressBar.isHidden = true
                    self.mainView.toolbarView.shareBarButtonItem.isEnabled = true
                } else if progress == 0 {
                    self.mainView.searchBarContainer.searchBarView.progressBar.isHidden = true
                } else {
                    self.mainView.searchBarContainer.searchBarView.progressBar.isHidden = false
                    self.mainView.toolbarView.shareBarButtonItem.isEnabled = false
                }
            }
            .store(in: &subscriptions)
    }
}

//MARK: Url managment
extension BrowserHomeViewController {
    func urlManagment(_ url: String) {
        searchRequestURL = url
        openSearchResult()
    }
}