//
//  MoleculeStackView.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 2/11/19.
//  Copyright © 2019 Verizon Wireless. All rights reserved.
//
//  This is a dynamic stack view that creates molecules if needed on set.

import UIKit


open class MoleculeStackView: Stack<StackModel> {
    
    var previousModel: MoleculeModelProtocol?
    
    /// Convenience function, adds a molecule to a MoleculeStackItem to the MoleculeStack
    func setup(with views: [View], lastItem: Bool) {
        
        var models: [MoleculeStackItemModel] = []
        
        for view in views {
            guard let model = view.model else { return }
            let stackItemModel = MoleculeStackItemModel(with: model)
            let stackItem = MoleculeStackItem(andContain: view)
            stackItems.append(stackItem)
            models.append(stackItemModel)
        }
        
        if let stackModel = stackModel {
            stackModel.molecules = models
        } else {
            model = StackModel(molecules: models)
        }
        
        restack()
    }
    
    // MARK: - Adding to stack
    /// Can be subclassed to create views when we get stack item models and have no views yet
    open func createStackItemsFromModel(_ model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
        
        guard let stackItemModels = stackModel?.molecules else { return }
        
        for model in stackItemModels {
            if let stackItem = ModelRegistry.createMolecule(model, delegateObject: delegateObject, additionalData: additionalData) as? MoleculeStackItem {
                stackItems.append(stackItem)
            }
        }
    }
    
    open override func setStackItemsFromModel(_ model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
        // If the items in the stack are different, clear them, create new ones.
        if (previousModel == nil) || Self.nameForReuse(with: previousModel!, delegateObject) != Self.nameForReuse(with: model, delegateObject) {
            removeAllItemViews()
            stackItems = []
            createStackItemsFromModel(model, delegateObject, additionalData)
        } else {
            super.setStackItemsFromModel(model, delegateObject, additionalData)
        }
    }
    
    open override func set(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
        previousModel = self.model
        super.set(with: model, delegateObject, additionalData)
    }
}
