TabsViewController.swift 6.07 KB
//
//  TabsViewController.swift
//  browser
//
//  Created by Artem Talko on 28.09.2023.
//

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() {
        setupCollectionView()
        addTargets()
        view.backgroundColor = UIColor(red: 0.984, green: 0.984, blue: 0.984, alpha: 1)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    }
    
    override func viewIsAppearing(_ animated: Bool) {
        refreshData()
        setCountOfTabs()
        navigationController?.isNavigationBarHidden = true
    }
    
    override func loadView() {
        view = mainView
    }
    
    init() {
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


//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", for: indexPath) as? OpenedTabsCollectionViewCell else {
            return OpenedTabsCollectionViewCell()
        }
        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)
    }
    
    private func setupCollectionView() {
        mainView.openedTabsCollectionView.dataSource = self
        mainView.openedTabsCollectionView.delegate = self
        mainView.openedTabsCollectionView.register(OpenedTabsCollectionViewCell.self, forCellWithReuseIdentifier: "OpenedTabsCollectionViewCell")
    }
}


//MARK: - Action
extension TabsViewController {
    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 addTargets() {
        addToolbarTargets()
    }
    
    private func addToolbarTargets() {
        mainView.tabsToolbarView.action = didTabButtonTapped
    }
    
    func getCellIndex() -> IndexPath {
        return cellIndexPathForTransition ?? IndexPath(row: tabsData.count - 1, section: 0)
    }
    
    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()
            }
        }
    }
    
    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)
        }
    }
    
    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()
        })
    }
    func setCountOfTabs() {
        mainView.tabsToolbarView.showTabToolbarButtonItem.title = "\(tabsData.count) Tabs"
    }
}