//
//  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)
        
        //set context value for 'primary' style to be set for the primaryButton in case the
        //property is not returned in the JSON and once decoded, this value is removed from the context
        try decoder.setContext(value: Styler.Button.Style.primary, for: "style") {
            self.primaryButton = try typeContainer.decodeMoleculeIfPresent(codingKey: .primaryButton)
        }
        
        //set context value for 'secondary' style to be set for the primaryButton in case the
        //property is not returned in the JSON and once decoded, this value is removed from the context
        try decoder.setContext(value: Styler.Button.Style.secondary, for: "style") {
            self.secondaryButton = try typeContainer.decodeMoleculeIfPresent(codingKey: .secondaryButton)
        }
    }
    
    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)
    }
}
