//
//  ThreeLayerModelBase.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 4/21/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//


@objcMembers open class ThreeLayerModelBase: TemplateModel, ThreeLayerTemplateModelProtocol {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    
    public var anchorHeader: Bool = false
    public var header: MoleculeModelProtocol?
    public var anchorFooter: Bool = false
    public var footer: MoleculeModelProtocol?
    
    public override var rootMolecules: [MoleculeModelProtocol] {
        [navigationBar, header, footer].compactMap { $0 }
    }
    
    //--------------------------------------------------
    // MARK: - Init
    //--------------------------------------------------
    
    public override init(pageType: String) {
        super.init(pageType: pageType)
    }
    
    //--------------------------------------------------
    // MARK: - Keys
    //--------------------------------------------------
    
    private enum CodingKeys: String, CodingKey {
        case anchorHeader
        case header
        case anchorFooter
        case footer
    }
    
    //--------------------------------------------------
    // MARK: - Codec
    //--------------------------------------------------
    
    required public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        if let anchor = try typeContainer.decodeIfPresent(Bool.self, forKey: .anchorHeader) {
            anchorHeader = anchor
        }
        header = try typeContainer.decodeModelIfPresent(codingKey: .header)
        if let anchor = try typeContainer.decodeIfPresent(Bool.self, forKey: .anchorFooter) {
            anchorFooter = anchor
        }
        footer = try typeContainer.decodeModelIfPresent(codingKey: .footer)
        try super.init(from: decoder)
    }
    
    public override func encode(to encoder: Encoder) throws {
        try super.encode(to: encoder)
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encodeIfPresent(anchorHeader, forKey: .anchorHeader)
        try container.encodeModelIfPresent(header, forKey: .header)
        try container.encodeIfPresent(anchorFooter, forKey: .anchorFooter)
        try container.encodeModelIfPresent(footer, forKey: .footer)
    }
}
