//
//  RuleAnyModelProtocol.swift
//  MVMCoreUI
//
//  Created by Matt Bruce on 3/9/22.
//  Copyright © 2022 Verizon Wireless. All rights reserved.
//

import Foundation

/// RuleAnyModelProtocol was abstracted to 1 place since this code was currently
/// duplicated in 2 classes.
/// This protocol should be used for the rules that need to Loop through all of the fields
/// and if ANY formField's isValid == TRUE, the Rule is then TRUE
public protocol RuleAnyModelProtocol: RulesProtocol{}

extension RuleAnyModelProtocol {
    
    /// Overriding the RulesProtocol default implementation 
    public func validate(_ fieldMolecules: [String: FormFieldProtocol],_ previousFieldValidity: [String: FormFieldValidity]) -> (valid: Bool, fieldValidity: [String: FormFieldValidity]) {

        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.valid, fieldValidity {
                fieldValidity = false
            }

            // If TRUE the RULE is TRUE, even if there are many fields to check.
            if fieldValidity {
                return (true, previousFieldValidity)
            }
        }

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