//
//  Container.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 12/11/19.
//  Copyright © 2019 Verizon Wireless. All rights reserved.
//

import UIKit


open class Container: View, ContainerProtocol {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    
    public var view: UIView?
    public let containerHelper = ContainerHelper()
    
    public var containerModel: ContainerModelProtocol? {
        get { model as? ContainerModelProtocol }
    }
    
    //--------------------------------------------------
    // MARK: - MoleculeViewProtocol
    //--------------------------------------------------
    
    override open func set(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
        super.set(with: model, delegateObject, additionalData)
        
        guard let containerModel = model as? ContainerModelProtocol else { return }
        
        containerHelper.set(with: containerModel, for: view as? MVMCoreUIViewConstrainingProtocol)
    }
    
    override open func reset() {
        super.reset()
        (view as? MoleculeViewProtocol)?.reset()
    }
    
    //--------------------------------------------------
    // MARK: - ContainerProtocol
    //--------------------------------------------------
    
    open func alignHorizontal(_ alignment: UIStackView.Alignment) {
        containerHelper.alignHorizontal(alignment)
    }
    
    open func alignVertical(_ alignment: UIStackView.Alignment) {
        containerHelper.alignVertical(alignment)
    }
    
    open func constrainView(_ view: UIView) {
        containerHelper.constrainView(view)
    }

    // MARK: - MVMCoreViewProtocol
    open override func updateView(_ size: CGFloat) {
        super.updateView(size)
        (view as? MVMCoreViewProtocol)?.updateView(size)
        containerHelper.updateViewMargins(self, model: containerModel, size: size)
    }

    /// Will be called only once.
    open override func setupView() {
        super.setupView()
        isAccessibilityElement = false
        backgroundColor = .clear
    }

    open func addAndContain(_ view: UIView) {
        view.translatesAutoresizingMaskIntoConstraints = false
        addSubview(view)
        containerHelper.constrainView(view)
        self.view = view
    }

    convenience init(andContain view: UIView) {
        self.init()
        addAndContain(view)
    }
}
