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


@objcMembers public class CollectionTemplateModel: ThreeLayerModelBase {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    
    public override class var identifier: String { "collection" }
    public var molecules: [CollectionItemModelProtocol & MoleculeModelProtocol]?
    public var columns: Int?
    
    public override var rootMolecules: [MoleculeModelProtocol] {
        if let molecules = molecules {
            return super.rootMolecules + molecules
        }
        return super.rootMolecules
    }

    //--------------------------------------------------
    // MARK: - Initializer
    //--------------------------------------------------
    
    public init(pageType: String, screenHeading: String?, molecules: [CollectionItemModelProtocol & MoleculeModelProtocol]) {
        super.init(pageType: pageType)
        self.screenHeading = screenHeading
        self.molecules = molecules
    }
    
    //--------------------------------------------------
    // MARK: - Keys
    //--------------------------------------------------
    
    private enum CodingKeys: String, CodingKey {
        case molecules
        case columns
    }
    
    //--------------------------------------------------
    // MARK: - Codec
    //--------------------------------------------------
    
    required public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        molecules = try typeContainer.decodeModelsIfPresent(codingKey: .molecules)
        columns = try typeContainer.decodeIfPresent(Int.self, forKey: .columns)
        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.encodeModelsIfPresent(molecules, forKey: .molecules)
        try container.encodeIfPresent(columns, forKey: .columns)
    }
}
