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


public protocol PageBehaviorHandlerProtocol {
    var behaviors: [PageBehaviorProtocol]? { get set }
}

public extension PageBehaviorHandlerProtocol {
    /// Creates the behaviors and sets the variable.
    mutating func createBehaviors(for model: PageBehaviorHandlerModelProtocol, delegateObject: MVMCoreUIDelegateObject?) {
        guard let behaviorModels = model.behaviors else {
            behaviors = nil
            return
        }
        
        var behaviors: [PageBehaviorProtocol] = []
        
        for behaviorModel in behaviorModels {
            do {
                let handlerType = try ModelRegistry.getHandler(behaviorModel) as! PageBehaviorProtocol.Type
                let behavior = handlerType.init(model: behaviorModel, delegateObject: delegateObject)
                behaviors.append(behavior)
            } catch {
                if let errorObject = MVMCoreErrorObject.createErrorObject(for: error, location: #function) {
                    MVMCoreLoggingHandler.addError(toLog: errorObject)
                }
            }
        }
        self.behaviors = behaviors.count > 0 ? behaviors : nil
    }
}
