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

import Foundation


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

    public func isValid(_ formField: FormFieldProtocol) -> Bool {
        return false
    }

    public func validate(_ fieldMolecules: [String: FormFieldProtocol],_ previousFieldValidity: [String: Bool]) -> (valid: Bool, fieldValidity: [String: Bool]) {
        var valid = true
        var compareValue: AnyHashable?
        var previousValidity: [String: Bool] = [:]

        for formKey in fields {
            guard let formField = fieldMolecules[formKey] else { continue }

            if compareValue == nil {
                compareValue = formField.formFieldValue()
                continue
            }

            if compareValue != formField.formFieldValue() {
                valid = false
                break
            } else {
                var fieldValidity = valid
                // 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
                }
            }
            previousValidity[formKey] = valid

        }
        return (valid: valid, fieldValidity: previousValidity)
    }
}
