//
//  TwoButtonViewModel.swift
//  MVMCoreUI
//
//  Created by Scott Pfeil on 1/13/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import UIKit


public class TwoButtonViewModel: ParentMoleculeModelProtocol {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    
    public static var identifier: String = "twoButtonView"
    public var backgroundColor: Color?
    public var primaryButton: ButtonModel?
    public var secondaryButton: ButtonModel?
    
    public var children: [MoleculeModelProtocol] {
        return [primaryButton, secondaryButton].compactMap { $0 }
    }
    
    //--------------------------------------------------
    // MARK: - Keys
    //--------------------------------------------------
    
    private enum CodingKeys: String, CodingKey {
        case moleculeName
        case backgroundColor
        case primaryButton
        case secondaryButton
    }
    
    //--------------------------------------------------
    // MARK: - Initialzer
    //--------------------------------------------------
    
    public init(_ primaryButton: ButtonModel?, _ secondaryButton: ButtonModel?) {
        self.primaryButton = primaryButton
        self.secondaryButton = secondaryButton
    }
    
    //--------------------------------------------------
    // MARK: - Codec
    //--------------------------------------------------
    
    required public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        backgroundColor = try typeContainer.decodeIfPresent(Color.self, forKey: .backgroundColor)
        primaryButton = try typeContainer.decodeMoleculeIfPresent(codingKey: .primaryButton)
        if primaryButton?.style == nil {
            primaryButton?.style = .primary
        }
        secondaryButton = try typeContainer.decodeMoleculeIfPresent(codingKey: .secondaryButton)
        if secondaryButton?.style == nil {
            secondaryButton?.style = .secondary
        }
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(moleculeName, forKey: .moleculeName)
        try container.encodeIfPresent(backgroundColor, forKey: .backgroundColor)
        try container.encodeIfPresent(primaryButton, forKey: .primaryButton)
        try container.encodeIfPresent(secondaryButton, forKey: .secondaryButton)
    }
}
