//
//  FormRule.swift
//  MVMCoreUI
//
//  Created by Suresh, Kamlesh on 2/24/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//
//  Used by the form validator for storing the rules for a particular group.

import Foundation

open class FormGroupRule: RulesContainerProtocol, Codable {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    
    public var groupName: String
    public var rules: [RulesProtocol]
    public var effects: [FormFieldEffectProtocol]?;
    //--------------------------------------------------
    // MARK: - Initializer
    //--------------------------------------------------
    
    public init(_ groupName: String, _ rules: [RulesProtocol], _ effects: [FormFieldEffectProtocol]) {
        self.groupName = groupName
        self.rules = rules
        self.effects = effects
    }

    //--------------------------------------------------
    // MARK: - Keys
    //--------------------------------------------------
    
    private enum CodingKeys: String, CodingKey {
         case groupName
         case rules
         case effects
    }

    //--------------------------------------------------
    // MARK: - Codec
    //--------------------------------------------------
    
    required public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        self.groupName = try typeContainer.decode(String.self, forKey: .groupName)
        self.rules = try typeContainer.decodeModels(codingKey: .rules)
        self.effects = try typeContainer.decodeModelsIfPresent(codingKey: .effects)
    }

    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(groupName, forKey: .groupName)
        try container.encodeModels(rules, forKey: .rules)
    }
}

