//
//  RuleEqualsIgnoreCaseModel.swift
//  MVMCoreUI
//
//  Created by Kevin Christiano on 5/15/20.
//  Copyright © 2020 Verizon Wireless. All rights reserved.
//

import Foundation


public class RuleEqualsIgnoreCaseModel: RulesProtocol {
    //--------------------------------------------------
    // MARK: - Properties
    //--------------------------------------------------
    
    public static var identifier: String = "equalsIgnoreCase"
    public var type: String = RuleEqualsIgnoreCaseModel.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 = false
        var compareText: String?

        var previousValidity: [String: Bool] = [:]
        for formKey in fields {
            guard let formField = fieldMolecules[formKey] else { continue }

            guard let compareString = compareText else {
                compareText = formField.formFieldValue() as? String
                continue
            }
            
            if let fieldValue = formField.formFieldValue() as? String,
                compareString.caseInsensitiveCompare(fieldValue) == .orderedSame {
                valid = true

                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
                }

                break
            }

            previousValidity[formKey] = valid
        }
        return (valid: valid, fieldValidity: previousValidity)
    }
}
