//
//  CoureUIUtility.swift
//  MVMCoreUI
//
//  Created by Kevin Christiano on 7/29/21.
//  Copyright © 2021 Verizon Wireless. All rights reserved.
//

import UIKit


public extension MVMCoreUIUtility {
    
    /// Finds a view by a given type.
    /// - Parameters:
    ///   - type: The type you are looking for.
    ///   - views: The starting array of subviews.
    /// - Returns: If found, the first view matching the type will be casted to it and returned; otherwise nil will be returned.
    static func findView<T>(by type: T.Type, views: [UIView]) -> T? {
        
        guard !views.isEmpty else { return nil }
        
        var queue = [UIView]()
        
        for view in views {
            if view is T {
                return view as? T
            }
            
            queue.append(contentsOf: view.subviews)
        }
        
        return findView(by: type, views: queue)
    }
    
    
    /// Finds an array of views assocaited with a given type.
    /// - Parameters:
    ///   - type: The type you are looking for.
    ///   - views: The starting array of subviews.
    /// - Returns: Will return an array of any view associated with the given type. Will return an empty array of none were found.
    static func findViews<T>(by type: T.Type, views: [UIView]) -> [T] {
        
        guard !views.isEmpty else { return [] }
        
        var queue = [UIView]()
        var matching = [T]()
        
        for view in views {
            if view is T {
                matching.append(view as! T)
            }
            
            queue.append(contentsOf: view.subviews)
        }
        
        return findViews(by: type, views: queue) + matching
    }
}
