//
//  GenericContentView.swift
//  GenericContentView
//
//  Created by James Magahern on 6/29/21.
//

import UIKit

class GenericContentView<View, Configuration> : UIView, UIContentView
    where View: UIView, Configuration: UIContentConfiguration
{
    typealias Applicator = (Configuration, View) -> Void
    
    var insets:     UIEdgeInsets = .zero
    let applicator: Applicator
    let view:       View
    
    var configuration: UIContentConfiguration {
        didSet {
            guard let config = configuration as? Configuration else { return }
            apply(config)
        }
    }
    
    init(configuration: Configuration, view: View, applicator: @escaping Applicator) {
        self.configuration = configuration
        self.view = view
        self.applicator = applicator
        super.init(frame: .zero)
        addSubview(view)
        
        view.translatesAutoresizingMaskIntoConstraints = false
        
        let guide = layoutMarginsGuide
        NSLayoutConstraint.activate([
            view.leadingAnchor.constraint(equalTo: guide.leadingAnchor),
            view.trailingAnchor.constraint(equalTo: guide.trailingAnchor),
            view.topAnchor.constraint(equalTo: guide.topAnchor),
            view.bottomAnchor.constraint(equalTo: guide.bottomAnchor),
        ])
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    internal func apply(_ configuration: Configuration) {
        applicator(configuration, view)
    }
}

