//
//  PageBehaviorConatinerModelProtocol.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 3/29/21.
//  Copyright © 2021 Verizon Wireless. All rights reserved.
//

/// Protocol applied to a model that contains a list of behavior models.
public protocol PageBehaviorContainerModelProtocol {
    var behaviors: [PageBehaviorModelProtocol]? { get set }
}

public extension PageBehaviorContainerModelProtocol {
    
    /// Adds the behavior model to the behaviors if possible.
    mutating func add(behavior: PageBehaviorModelProtocol) {
        var newBehaviors = behaviors ?? []
        guard !behavior.shouldAllowMultipleInstances,
              !newBehaviors.contains(where: { $0.behaviorName == behavior.behaviorName
              }) else { return }
        
        newBehaviors.append(behavior)
        self.behaviors = newBehaviors
    }
}

public extension PageBehaviorContainerModelProtocol where Self: MoleculeTreeTraversalProtocol {
    
    /// Traverses all models and adds any required behavior models.
    mutating func traverseAndAddRequiredBehaviors() {
        let behaviorModels: [PageBehaviorModelProtocol] = reduceDepthFirstTraverse(options: .childFirst, depth: 0, initialResult: []) { (accumulator, molecule, depth) in
            if let behaviorRequirer = molecule as? PageBehaviorProtocolRequirer {
                return accumulator + behaviorRequirer.getRequiredBehaviors()
            }
            return accumulator
        }
        for behavior in behaviorModels {
            add(behavior: behavior)
        }
    }
}
