TabsViewController.swift 6.15 KB
//
//  TabsViewController.swift
//  browser
//
//  Created by Artem Talko on 28.09.2023.
//
//MARK: Checked

import UIKit
import RealmSwift
import Realm

final class TabsViewController: UIViewController {
    private var tabsData: [BrowserTabDataBase] = []
    
    var cellIndexPathForTransition: IndexPath?
    let mainView = TabsView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initViewController()
    }
    
    private func initViewController() {
        view.backgroundColor = UIColor(red: 0.984, green: 0.984, blue: 0.984, alpha: 1)
        
        setupCollectionView()
        addTargets()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewIsAppearing(_ animated: Bool) {
        navigationController?.isNavigationBarHidden = true
        
        refreshData()
        setCountOfTabs()
    }
    
    override func loadView() {
        view = mainView
    }
}


//MARK: CollectionView
extension TabsViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
     func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return tabsData.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let tab = tabsData[indexPath.row]
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: OpenedTabsCollectionViewCell.cellID, for: indexPath) as? OpenedTabsCollectionViewCell else {
            return UICollectionViewCell()
        }
        cell.model = tab
        cell.delegate = self
        cell.closeTabButton.addTarget(self, action: #selector(closeTab(_:)), for: .touchUpInside)
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 163.sizeW, height: 184.sizeH)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        cellIndexPathForTransition = indexPath
        pushSelectedTab(indexPath)
    }
    
}


//MARK: - Action
extension TabsViewController {
    private func didTabButtonTapped(type: HistoryToolbarElementType) {
        switch type {
        case .add:
            addNewDefaultTab()
            refreshData()
            
            let lastIndex = tabsData.endIndex - 1
            let lastIndexPath = IndexPath(row: lastIndex, section: 0)
            
            cellIndexPathForTransition = lastIndexPath
            pushSelectedTab(lastIndexPath)
            break
            
        case .done:
            refreshData()
            
            let lastIndex = tabsData.endIndex - 1
            let lastIndexPath = IndexPath(row: lastIndex, section: 0)
            
            cellIndexPathForTransition = lastIndexPath
            pushSelectedTab(lastIndexPath)
            break
            
        default:
            break
        }
    }
    
    @objc
    private func closeTab(_ sender: TabCollectionViewCell) {}
}


//MARK: - Helpers
extension TabsViewController {
    private func setupCollectionView() {
        mainView.openedTabsCollectionView.dataSource = self
        mainView.openedTabsCollectionView.delegate = self
        mainView.openedTabsCollectionView.register(OpenedTabsCollectionViewCell.self, forCellWithReuseIdentifier: OpenedTabsCollectionViewCell.cellID)
    }
    
    private func addTargets() {
        addToolbarTargets()
    }
    
    private func addToolbarTargets() {
        mainView.tabsToolbarView.action = didTabButtonTapped
    }
    
    func getCellIndex() -> IndexPath {
        return cellIndexPathForTransition ?? IndexPath(row: tabsData.count - 1, section: 0)
    }
    
    private func addNewDefaultTab() {
        let defaultImage = UIImage(named: "defaultImage")
        
        TabManager.shared.saveTabWithComplition(tabTitle: "Start Page", snapshotImage: defaultImage, tabUrl: "homeUrl") { [weak self] result in
            switch result {
            default:
                self?.refreshData()
            }
        }
    }
    
    private func pushSelectedTab(_ indexPath: IndexPath) {
        let index = indexPath.row
        
        if tabsData[index].TabUrl != "homeUrl" {
            let browserHomeViewController = BrowserHomeViewController(url: tabsData[index].TabUrl, currentTabId: index)
            browserHomeViewController.urlManagment(tabsData[index].TabUrl)
            
            navigationController?.pushViewController(browserHomeViewController, animated: true)
        } else {
            let browserHomeViewController = BrowserHomeViewController(url: tabsData[index].TabUrl, currentTabId: index)
            
            navigationController?.pushViewController(browserHomeViewController, animated: true)
        }
    }
    
    private func refreshData() {
        tabsData = TabManager.shared.getAllTabs()
        mainView.openedTabsCollectionView.reloadData()
    }
}

//MARK: - Delete tab
extension TabsViewController: OpenedTabsCellDelegate {
    func deleteTabDelegateFunc(cell: OpenedTabsCollectionViewCell) {
        guard let indexPath = mainView.openedTabsCollectionView.indexPath(for: cell) else {
            return
        }
        
        tabsData.remove(at: indexPath.row)
        
        mainView.openedTabsCollectionView.performBatchUpdates({
            mainView.openedTabsCollectionView.deleteItems(at: [indexPath])
        }, completion: { _ in
            if self.tabsData.isEmpty {
                self.addNewDefaultTab()
                let browserHomeViewController = BrowserHomeViewController(url: "homeUrl", currentTabId:  self.tabsData.count - 1)
                
                self.navigationController?.pushViewController(browserHomeViewController, animated: true)
                
                self.cellIndexPathForTransition = IndexPath(row: self.tabsData.count - 1, section: 0)
            }
            self.setCountOfTabs()
        })
    }
    private func setCountOfTabs() {
        mainView.tabsToolbarView.showedCountOfTabs.title = "\(tabsData.count) Tabs"
    }
}