//
//  UICollectionView+Reusable.swift
//  WLReusable
//
//  Created by Mr.Wang on 2021/8/30.
//

import UIKit

public extension UICollectionView {
    
    func register<Cell: UICollectionViewCell>(_ cellType: Cell.Type) {
        register(cellType,
                 forCellWithReuseIdentifier: Cell.reuseIdentifier)
    }
    
    func register<View: UICollectionReusableView>(_ viewType: View.Type, forSupplementaryViewOfKind kind: String) {
        register(viewType,
                 forSupplementaryViewOfKind: kind,
                 withReuseIdentifier: View.reuseIdentifier)
    }
    
    func registerHeader<View: UICollectionReusableView>(_ viewType: View.Type) {
        register(viewType,
                 forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,
                 withReuseIdentifier: View.reuseIdentifier)
    }
    
    func registerFooter<View: UICollectionReusableView>(_ viewType: View.Type) {
        register(viewType,
                 forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter,
                 withReuseIdentifier: View.reuseIdentifier)
    }
    
    func dequeueReusableCell<Cell: UICollectionViewCell>(_ cellType: Cell.Type, for indexPath: IndexPath) -> Cell {
        guard let cell = dequeueReusableCell(withReuseIdentifier: Cell.reuseIdentifier,
                                             for: indexPath) as? Cell else {
            fatalError("Should register \(Cell.reuseIdentifier) brfore dequeue reusable cell.")
        }
        return cell
    }
    
    func dequeueReusableView<View: UICollectionReusableView>(_ viewType: View.Type, ofKind: String, for indexPath: IndexPath) -> View {
        guard let view = dequeueReusableSupplementaryView(ofKind: ofKind,
                                                          withReuseIdentifier: View.reuseIdentifier,
                                                          for: indexPath) as? View else {
            fatalError("Should register \(View.reuseIdentifier) brfore dequeue reusable view.")
        }
        return view
    }
}
