//
//  ToolbarButtonContainerView.swift
//  App
//
//  Created by James Magahern on 8/14/20.
//

import UIKit

class ToolbarButtonContainerView: UIView
{
    private var buttonViews: [UIView] = []
    
    public var numberOfButtonViews: Int { buttonViews.count }
    
    func addButtonView(_ button: UIView) {
        if let asButton = button as? UIButton {
            asButton.isPointerInteractionEnabled = true
        }
        
        buttonViews.append(button)
        addSubview(button)
        setNeedsLayout()
    }
    
    func removeAllButtonViews() {
        buttonViews.forEach { $0.removeFromSuperview() }
        buttonViews.removeAll()
        setNeedsLayout()
    }
    
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        let width: CGFloat = buttonViews.reduce(0.0) { (result, button) -> CGFloat in
            return result + button.sizeThatFits(size).width
        }
        
        return CGSize(width: width, height: size.height)
    }
    
    override func layoutSubviews() {
        var buttonRect = CGRect(origin: .zero, size: CGSize(width: 0, height: bounds.height))
        
        for button in buttonViews {
            let buttonSize = button.sizeThatFits(bounds.size)
            buttonRect.size = CGSize(width: buttonSize.width, height: bounds.height)
            button.frame = buttonRect
            
            buttonRect.origin.x += buttonRect.width
        }
    }
}
