//
//  ToolBarUIPickerView.swift
//  https://stackoverflow.com/questions/31728680/how-to-make-an-uipickerview-with-a-done-button
//  ABC Bluetooth Demo
//
//  Created by AB Circle on 19/11/2020.
//  Copyright © 2020-2024 AB Circle. All rights reserved.
//

import Foundation
import UIKit

/// Delegate protocol for delegate classes to implement
protocol ToolbarUIPickerViewDelegateProtocol: AnyObject {
    
    /// Handler to implement for when user taps the Done button
    func didTapDone()
    
    /// Handler to implement for when the user taps the Cancel button
    func didTapCancel()
}

/// Class creating an UI PickerView with a toolbar. The toolbar has 2 buttons; a 'Done' and a 'Cancel' button.
/// A protocol is defined so a host class using the ToolbarUIPickerView can become a delegate and implement the
/// didTapDone and didTapCancel methods for handling the 2 toolbar buttons.
class ToolbarUIPickerView: UIPickerView {
    
    /// Custom UIToolBar
    private(set) var toolbar: UIToolbar?
    
    /// toolbarDelegate, set this to the class acting as ToolbarUIPickerViewDelegate
    weak var toolbarDelegate: ToolbarUIPickerViewDelegateProtocol?
    
    /// Override Initialiser
    ///
    /// - Parameter frame: CGRect
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.commonInit()
    }
    
    /// Required initialiser
    ///
    /// - Parameter aDecoder: NSCoder
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.commonInit()
    }
    
    /// Initialises the toolbar and its properties
    private func commonInit() {
        let toolBar = UIToolbar()
        toolBar.barStyle = UIBarStyle.default
        toolBar.isTranslucent = true
        toolBar.tintColor = .systemBlue
        toolBar.sizeToFit()

        let doneButton      = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.doneTapped))
        let spaceButton     = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let cancelButton    = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(self.cancelTapped))

        toolBar.setItems([cancelButton, spaceButton, doneButton], animated: false)
        toolBar.isUserInteractionEnabled = true

        self.toolbar = toolBar
        self.backgroundColor = .systemBackground
    }
    
    /// Action handler handling the tapping of the Done button.
    /// Forwards control to the toolbar delegate didTapDone method
    @objc func doneTapped() {
        self.toolbarDelegate?.didTapDone()
    }

    /// Action handler handling the tapping of the Cancel button.
    /// Forwards control to the toolbar delegate didTapCancel method
    @objc func cancelTapped() {
        self.toolbarDelegate?.didTapCancel()
    }
}
