//
//  CollectionView.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 4/10/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import Foundation

open class CollectionView: UICollectionView, MVMCoreViewProtocol {
    
    /// A block that gets called on tableview frame changes
    public var frameChangeAction: (() -> Void)?
    
    private var previousFrame = CGRect.zero
    
    private var initialSetupPerformed = false
    
    private func initialSetup() {
        if !initialSetupPerformed {
            initialSetupPerformed = true
            setupView()
        }
    }
    
    public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: layout)
        initialSetup()
    }
    
    required public init?(coder: NSCoder) {
        super.init(coder: coder)
        initialSetup()
    }
    
    open override func layoutSubviews() {
        super.layoutSubviews()
        if frame != previousFrame {
            frameChangeAction?()
        }
        previousFrame = frame
    }
    
    public func updateView(_ size: CGFloat) {
        for cell in visibleCells {
            (cell as? MVMCoreViewProtocol)?.updateView(size)
        }
        collectionViewLayout.invalidateLayout()
    }
    
    public func setupView() {
        translatesAutoresizingMaskIntoConstraints = false
        showsHorizontalScrollIndicator = false
        showsVerticalScrollIndicator = false
        backgroundColor = .clear
        isAccessibilityElement = false
        contentInsetAdjustmentBehavior = .always
    }
}
