//
//  ValidatorClass.swift
//  WOKA
//
//  Created by Bilal on 03/05/2024.
//

import UIKit

class ValidatorClass {
    static let sharedInstanec = ValidatorClass()
    
    func validateName(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let currentText = textField.text ?? ""
                    
        // dont allow leading space for names
        if (range.location == 0 && string == " ") {
            return false
        }
        
        // Check if the replacement string is valid (contains only letters and spaces)
        if !string.nameCharacterOnly(){return false}

        // Ensure that the first and last characters are not spaces
        if currentText.isEmpty && string == " " {
            return false
        }
        
        // Allow only one space between first name, middle name, and last name
        if string == " " {
            let components = currentText.components(separatedBy: " ")
            
            //Block user from adding 2 spaces in trailing word
            if components.last == "" && string == " "{
                return false
            }
            
            if (currentText as NSString).replacingCharacters(in: range, with: string).contains("  "){
                return false
            }
            
            let filteredComponents = components.filter { !$0.isEmpty }
            if filteredComponents.count >= 6 {
                return false
            }
        }
        
        // Check the length limit (e.g., adjust to your requirements)
        let newLength = currentText.count + string.count - range.length
        return newLength <= 50  // Adjust the limit as needed.
    }

    func limitCharacter(length : Int, _ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
        let maxLength = length
        let currentString = (textField.text ?? "") as NSString
        let newString = currentString.replacingCharacters(in: range, with: string)
        return newString.count <= maxLength
    }
    
    func limitCharacterTV(length : Int, _ textView: UITextView, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
        let maxLength = length
        let currentString = (textView.text ?? "") as NSString
        let newString = currentString.replacingCharacters(in: range, with: string)
        return newString.count <= maxLength
    }
}
