//
//  HPickerViewController.swift
//  Tool
//
//  Created by ldc on 2021/5/8.
//

import UIKit

protocol HPickable {
    
    var title: String { get }
}

class HPickerViewController: UIViewController {
    
    @IBOutlet weak var pickerView: UIPickerView!
    
    var pickables: [HPickable] = []
    
    var didCompleteClosure: ((HPickable?) -> Void)?
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        modalPresentationStyle = .overCurrentContext
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func cancelAction(_ sender: Any) {
        
        dismiss(animated: true, completion: {
            self.didCompleteClosure?(nil)
        })
    }
    
    @IBAction func doneAction(_ sender: Any) {
        
        if pickables.count > pickerView.selectedRow(inComponent: 0) {
            let index = pickerView.selectedRow(inComponent: 0)
            dismiss(animated: true, completion: {
                self.didCompleteClosure?(self.pickables[index])
            })
        }
    }
}

extension HPickerViewController: UIPickerViewDataSource, UIPickerViewDelegate {
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        
        return pickables.count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        
        return pickables[row].title
    }
}
