//
//  HeadlineBody.swift
//  MVMCoreUI
//
//  Created by Suresh, Kamlesh on 10/3/19.
//  Copyright © 2019 Suresh, Kamlesh. All rights reserved.
//


@objcMembers open class HeadlineBodyModel: ParentMoleculeModelProtocol {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    
    public static var identifier: String = "headlineBody"
    public var moleculeName: String = HeadlineBodyModel.identifier
    public var headline: LabelModel?
    public var body: LabelModel?
    public var style: Style?
    public var backgroundColor: Color?
    
    public var children: [MoleculeModelProtocol] {
        [headline, body].compactMap { $0 }
    }
    
    //--------------------------------------------------
    // MARK: - Enum
    //--------------------------------------------------
    
    /// Convenience styles for common situations.
    public enum Style: String, Codable {
        case landingHeader
        case header
        case itemHeader
        case item
    }
    
    //--------------------------------------------------
    // MARK: - Initializers
    //--------------------------------------------------

    public init(headline: LabelModel) {
        self.headline = headline
    }
    
    public init(body: LabelModel) {
        self.body = body
    }
    
    //-----------------------------------------------------
    // MARK: - Codec
    //-----------------------------------------------------
    
    private enum CodingKeys: String, CodingKey {
        case moleculeName
        case headline
        case body
        case style
        case backgroundColor
    }
    
    required public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        headline = try typeContainer.decodeMoleculeIfPresent(codingKey: .headline)
        body = try typeContainer.decodeMoleculeIfPresent(codingKey: .body)
        style = try typeContainer.decodeIfPresent(Style.self, forKey: .style)
        backgroundColor = try typeContainer.decodeIfPresent(Color.self, forKey: .backgroundColor)
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(moleculeName, forKey: .moleculeName)
        try container.encodeIfPresent(headline, forKey: .headline)
        try container.encodeIfPresent(body, forKey: .body)
        try container.encodeIfPresent(style, forKey: .style)
        try container.encodeIfPresent(backgroundColor, forKey: .backgroundColor)
    }
}
