//
//  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
        }
    }
    
    /// Helper function to do common parsing logic.
    func parseTemplate(json: [AnyHashable: Any]?) throws {
        guard let pageJSON = json else { return }
        let delegateObject = (self as? MVMCoreViewControllerProtocol)?.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 behaviorHandlerModel = templateModel as? TemplateModelProtocol & PageBehaviorHandlerModelProtocol,
              var behaviorHandler = self as? PageBehaviorHandlerProtocol else { return }
        behaviorHandlerModel.traverseAndAddRequiredBehaviors()
        behaviorHandler.createBehaviors(for: behaviorHandlerModel, delegateObject: delegateObject)
        if let viewController = self as? UIViewController {
            MVMCoreUISession.sharedGlobal()?.applyGlobalBehaviors(to: viewController)
        }
    }
    
    func decodeTemplate(using decoder: JSONDecoder, from data: Data) throws -> TemplateModel {
        try decoder.decode(TemplateModel.self, from: data)
    }
}
