//
//  ModelTemplateProtocol.swift
//  MVMCoreUI
//
//  Created by Suresh, Kamlesh on 11/25/19.
//  Copyright © 2019 Verizon Wireless. All rights reserved.
//

import Foundation

public protocol TemplateProtocol: AnyObject, PageProtocol {
    associatedtype TemplateModel: TemplateModelProtocol
    var templateModel: TemplateModel? { get set }
    
    func decodeTemplate(using decoder: JSONDecoder, from data: Data) throws -> TemplateModel
}

public extension TemplateProtocol {
    
    // Utilize existing underlying property
    var templateModel: TemplateModel? {
        get {
            pageModel as? TemplateModel
        }
        set {
            var mutableSelf = self
            mutableSelf.pageModel = newValue
        }
    }
    
    func decodeTemplate(using decoder: JSONDecoder, from data: Data) throws -> TemplateModel {
        try decoder.decode(TemplateModel.self, from: data)
    }
}

public extension TemplateProtocol where Self: PageBehaviorHandlerProtocol, Self: MVMCoreViewControllerProtocol {
    
    /// Helper function to do common parsing logic.
    func parseTemplate(json: [AnyHashable: Any]?) throws {
        guard let pageJSON = json else { return }
        let delegateObject = delegateObject?() as? MVMCoreUIDelegateObject
        let data = try JSONSerialization.data(withJSONObject: pageJSON)
        let decoder = JSONDecoder.create(with: delegateObject)
        templateModel = try decodeTemplate(using: decoder, from: data)
        
        // Add additional required behaviors if applicable.
        guard var pageBehaviorsModel = templateModel as? TemplateModelProtocol & PageBehaviorContainerModelProtocol else  { return }
        
        pageBehaviorsModel.traverseAndAddRequiredBehaviors()
        var behaviorHandler = self
        behaviorHandler.applyBehaviors(pageBehaviorModel: pageBehaviorsModel, delegateObject: delegateObject)
    }
}
