//
//  RuleAnyRequiredModel.swift
//  MVMCoreUI
//
//  Created by Kevin Christiano on 3/13/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import UIKit


public class RuleAnyRequiredModel: RulesProtocol {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------

    public static var identifier: String = "anyRequired"
    public var type: String = RuleRequiredModel.identifier
    public var ruleId: String? 
    public var fields: [String]
    public var errorMessage: [String: String]?
    
    //--------------------------------------------------
    // MARK: - Methods
    //--------------------------------------------------
    
    public func isValid(_ formField: FormFieldProtocol) -> Bool {
        guard let value = formField.formFieldValue() else { return false }
        
        if let valueString = value as? String {
            return valueString.count > 0
            
        } else if let valueBool = value as? Bool {
            return valueBool
        }
        
        return false
    }
    
    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 (fieldValidity, previousValidity)
            } 
        }

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