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

import Foundation

@objcMembers open class MoleculeSectionFooter: SectionHeaderFooterView {
    open var molecule: MoleculeViewProtocol?
    public let containerHelper = ContainerHelper()

    /// Adds the molecule to the view.
    open func addMolecule(_ molecule: MoleculeViewProtocol) {
        contentView.addSubview(molecule)
        containerHelper.constrainView(molecule)
        self.molecule = molecule
    }
    
    open override func updateView(_ size: CGFloat) {
        super.updateView(size)
        containerHelper.updateViewMargins(self, model: model as? MoleculeSectionFooterModel, size: size)
        contentView.directionalLayoutMargins = directionalLayoutMargins
        (molecule as? MVMCoreViewProtocol)?.updateView(size)
    }
    
    open override func set(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
        super.set(with: model, delegateObject, additionalData)
        guard let model = model as? MoleculeSectionFooterModel else { return }
        if molecule != nil {
            molecule?.set(with: model.molecule, delegateObject, additionalData)
        } else if let moleculeView = ModelRegistry.createMolecule(model.molecule, delegateObject: delegateObject, additionalData: additionalData) {
            addMolecule(moleculeView)
        }
        containerHelper.set(with: model, for: molecule as? MVMCoreUIViewConstrainingProtocol)
    }
    
    open override func reset() {
        super.reset()
        molecule?.reset()
    }

    public override class func nameForReuse(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?) -> String? {
        return MoleculeContainer.nameForReuse(with: model, delegateObject)
    }
    
    public override class func requiredModules(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, error: AutoreleasingUnsafeMutablePointer<MVMCoreErrorObject?>?) -> [String]? {
        return MoleculeContainer.requiredModules(with: model, delegateObject, error: error)
    }
    
    public override class func estimatedHeight(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?) -> CGFloat? {
        return MoleculeContainer.estimatedHeight(with: model, delegateObject) ?? 80.0
    }
}
