//
//  UIToolbar+Extension.swift
//  MVMCoreUI
//
//  Created by Kevin Christiano on 4/10/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import Foundation

public protocol TextFieldOrView { }

extension UITextView: TextFieldOrView { }
extension UITextField: TextFieldOrView { }


public extension UIToolbar {
    
    class func createEmptyToolbar() -> UIToolbar {
        
        let toolbar = UIToolbar(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44))
        toolbar.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleWidth]
        toolbar.barStyle = .default
        toolbar.barTintColor = .mvmCoolGray3
        toolbar.tintColor = .mvmBlack
        toolbar.isTranslucent = true
        
        return toolbar
    }
    
    class func getToolbarWithDoneButton(delegate: Any?, action: Selector) -> UIToolbar {
        
        let toolbar = createEmptyToolbar()
        let space = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let button = UIBarButtonItem(barButtonSystemItem: .done, target: delegate, action: action)
        toolbar.setItems([space, button], animated: false)
        
        return toolbar
    }
    
    class func addDismissToolbar(to object: TextFieldOrView, delegate: Any?, action: Selector) {
        
        let toolbar = Self.getToolbarWithDoneButton(delegate: delegate, action: action)
        
        switch object {
        case is UITextField:
            (object as? UITextField)?.inputAccessoryView = toolbar
            
        case is UITextView:
            (object as? UITextView)?.inputAccessoryView = toolbar
            
        default:
            return
        }
    }
}
