//
//  UITextField+Extension.swift
//  galaxy
//
//  Created by edy on 2024/3/5.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

extension UITextField {
    
    /// 限制textField输入
    public func limitInputWithPattern(pattern: String, _ limitCount: Int = -1) {
        // 非markedText才继续往下处理
        guard let _: UITextRange = self.markedTextRange else {
            // 当前光标的位置（后面会对其做修改）
            let cursorPostion = self.offset(from: self.endOfDocument, to: self.selectedTextRange!.end)
            // 替换后的字符串
            var str = ""
            if pattern == "" {
                str = self.text!
            } else {
                str = self.text!.regularReplace(pattern: pattern, with: "")
            }
            // 如果长度超过限制则直接截断
            if limitCount >= 0, str.count > limitCount {
                str = String(str.prefix(limitCount))
            }
            self.text = str
            // 让光标停留在正确位置
            let targetPostion = self.position(from: self.endOfDocument, offset: cursorPostion)!
            self.selectedTextRange = self.textRange(from: targetPostion, to: targetPostion)
            return
        }
    }
}

extension String {
 
    // 使用正则表达式替换
    func regularReplace(pattern: String, with: String, options: NSRegularExpression.Options = []) -> String {
        do {
            let regex = try NSRegularExpression(pattern: pattern, options: options)
            return regex.stringByReplacingMatches(in: self, options: [],
                                                  range: NSRange(location: 0, length: self.count),
                                                  withTemplate: with)

        } catch {
            return ""
        }
    }
}
