//
//  RuleAnyModel.swift
//  MVMCoreUI
//
//  Created by Suresh, Kamlesh on 2/24/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import Foundation


public class RuleAnyValueChangedModel: RulesProtocol {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    
    public static var identifier: String = "anyValueChanged"
    public var type: String = RuleAnyValueChangedModel.identifier
    public var ruleId: String? 
    public var errorMessage: [String: String]?
    public var fields: [String]

    //--------------------------------------------------
    // MARK: - Validation
    //--------------------------------------------------
    
    public func isValid(_ formField: FormFieldProtocol) -> Bool {
        return formField.baseValue != formField.formFieldValue()
    }

    public func validate(_ fieldMolecules: [String: FormFieldProtocol],_ previousFieldValidity: [String: Bool]) -> (valid: Bool, fieldValidity: [String: Bool]) {
        var previousValidity: [String: Bool] = [:]
        for formKey in fields {
            guard let formField = fieldMolecules[formKey] else { continue }
            var fieldValidity = isValid(formField)
            // If past rule is invalid for a field, the current rule should not flip the validity of a field
            if let validity = previousFieldValidity[formKey], !validity, fieldValidity {
                fieldValidity = false
            }

            if fieldValidity {
                return (true, previousValidity)
            }
        }

        // if the rule breaks all fields should be set to false
        fields.forEach { (formKey) in
            previousValidity[formKey] = false
        }
        return (valid: false, fieldValidity: previousValidity)        
    }
}
