//
//  EnableFormFieldEffectModel.swift
//  MVMCoreUI
//
//  Created by Matt Bruce on 12/1/21.
//  Copyright © 2021 Verizon Wireless. All rights reserved.
//

import Foundation


public class EnableFormFieldEffectModel: FormFieldEffectProtocol {
    
    
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    
    public static var identifier: String = "enableFormFieldEffect"
    public var fieldKey: String = ""
    public var activatedRuleIds: [String]?
    public var rules: [RulesProtocol]
    
    init(_ fieldKey: String, activatedRuleIds: [String], rules: [RulesProtocol]) {
        self.fieldKey = fieldKey
        self.activatedRuleIds = activatedRuleIds
        self.rules = rules
    }
    
    //--------------------------------------------------
    // MARK: - Keys
    //--------------------------------------------------
    
    private enum CodingKeys: String, CodingKey {
        case fieldKey
        case activatedRuleIds
        case rules
    }
    
    //--------------------------------------------------
    // MARK: - Codec
    //--------------------------------------------------
    
    required public init(from decoder: Decoder) throws {
        let typeContainer = try decoder.container(keyedBy: CodingKeys.self)
        self.fieldKey = try typeContainer.decode(String.self, forKey: .fieldKey)
        self.activatedRuleIds = try typeContainer.decodeIfPresent([String].self, forKey: .activatedRuleIds)
        self.rules = try typeContainer.decodeModels(codingKey: .rules)
    }
    
    public func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        try container.encode(fieldKey, forKey: .fieldKey)
        try container.encode(activatedRuleIds, forKey: .activatedRuleIds)
        try container.encodeModels(rules, forKey: .rules)
    }
    
    public func setEffect(validity: Bool, field: FormFieldProtocol,form: FormValidator, group: FormGroupRule) {
        field.enabled = validity
        if let updateField = field as? UIUpdatableModelProtocol {
            updateField.updateUI?()
        }
    }
}
