TabsToolbarView.swift 2.8 KB
//
//  Tabs.swift
//  browser
//
//  Created by Artem Talko on 28.09.2023.
//

import UIKit

enum HistoryToolbarElementType {
    case add
    case tabs
    case done
}

final class TabsToolbarView: UIView {
    var action: ((HistoryToolbarElementType) -> Void)?
    
    private let toolbar: UIToolbar = {
        let obj = UIToolbar()
        obj.barTintColor = .white
        
        return obj
    }()
    
    private let newTabToolbarButtonItem: UIBarButtonItem = {
        let obj = UIBarButtonItem()
        obj.image = UIImage(systemName: "plus")
        obj.tintColor = .gray
        
        return obj
    }()
    
    
    let showedCountOfTabs: UIBarButtonItem = {
        let obj = UIBarButtonItem()
        obj.tintColor = .gray
        
        return obj
    }()
    
    private let doneTabToolbarButtonItem: UIBarButtonItem = {
        let obj = UIBarButtonItem()
        obj.title = "Done"
        
        return obj
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setup()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setup() {
        addSubview(toolbar)
        
        setupToolbar()
        initActions()
        setupConstraints()
    }
    
    private func setupConstraints() {
        toolbar.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(safeAreaLayoutGuide.snp.bottom)
        }
    }
}


// MARK: - Helpers
extension TabsToolbarView {
    private func initActions() {
        newTabToolbarButtonItem.target = self
        newTabToolbarButtonItem.action = #selector(didItemTapped(_:))
        
        showedCountOfTabs.target = self
        showedCountOfTabs.action = #selector(didItemTapped(_:))
        
        doneTabToolbarButtonItem.target = self
        doneTabToolbarButtonItem.action = #selector(didItemTapped(_:))
    }
    
    private func setupToolbar() {
        let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        toolbar.items = [ newTabToolbarButtonItem,
                          flexibleSpace, showedCountOfTabs,
                          flexibleSpace, doneTabToolbarButtonItem ]
        toolbar.backgroundColor = .white
    }
}

// MARK: - Actions
extension TabsToolbarView {
    @objc
    private func didItemTapped(_ sender: UIBarButtonItem) {
        guard let action else {
            return
        }
        switch sender {
            case newTabToolbarButtonItem:
                action(.add)
            case showedCountOfTabs:
                action(.tabs)
            case doneTabToolbarButtonItem:
                action(.done)
            default:
                break
        }
    }
}