TabsToolbarView.swift 2.64 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)?
    
    let toolbar: UIToolbar = {
        let obj = UIToolbar()
        obj.barTintColor = .white
        return obj
    }()
    
    let newTabToolbarButtonItem: UIBarButtonItem = {
        let obj = UIBarButtonItem()
        obj.image = UIImage(systemName: "plus")
        obj.tintColor = .gray
        return obj
    }()
    
   
    let showTabToolbarButtonItem: UIBarButtonItem = {
        let obj = UIBarButtonItem()
        obj.tintColor = .gray
        return obj
    }()
    
    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)
        let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        toolbar.items = [ newTabToolbarButtonItem,
                         flexibleSpace, showTabToolbarButtonItem,
                         flexibleSpace, doneTabToolbarButtonItem ]
        
        toolbar.backgroundColor = .white
        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(_:))
        showTabToolbarButtonItem.target = self
        showTabToolbarButtonItem.action = #selector(didItemTapped(_:))
        doneTabToolbarButtonItem.target = self
        doneTabToolbarButtonItem.action = #selector(didItemTapped(_:))
    }
}

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