//
//  String+Extension.swift
//  SpeakEasyLearnEnglish
//
//  Created by edy on 2025/7/3.
//

import UIKit


extension String {
    
    func loadData() -> Data? {
        let path = Bundle.main.bundleURL.appendingPathComponent("\(self).json")
        do{
            return try Data(contentsOf: path)
        }catch{
            return Data()
        }
    }
    
    func size(withFont font: UIFont, constrainedToWidth width: CGFloat = .greatestFiniteMagnitude) -> CGSize {
        let attributes = [NSAttributedString.Key.font: font]
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(
            with: constraintRect,
            options: [.usesLineFragmentOrigin, .usesFontLeading],
            attributes: attributes,
            context: nil
        )
        return CGSize(width: ceil(boundingBox.width), height: ceil(boundingBox.height))
    }
    
    /// 去掉首尾的特殊符号
    func whitespacesAndNew() -> String {
        return self.trimmingCharacters(in: .whitespacesAndNewlines)
    }
    
    /// 计算字符串在指定字体和约束高度下的显示尺寸
    func size(withFont font: UIFont, constrainedToHeight height: CGFloat) -> CGSize {
        let attributes = [NSAttributedString.Key.font: font]
        let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
        let boundingBox = self.boundingRect(
            with: constraintRect,
            options: [.usesLineFragmentOrigin, .usesFontLeading],
            attributes: attributes,
            context: nil
        )
        return CGSize(width: ceil(boundingBox.width), height: ceil(boundingBox.height))
    }
    
    ///  判断是否是邮箱
    func isValidEmail() -> Bool {
        let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
        let emailPredicate = NSPredicate(format: "SELF MATCHES %@", emailRegex)
        return emailPredicate.evaluate(with: self)
    }
    
    func localJson(_ fileName:String) -> String? {
        let path = Bundle.main.path(forResource: fileName, ofType: "json")
        return path
    }
    
    func attributed() -> AttributedStringBuilder {
        return AttributedStringBuilder(self)
    }
    // 支持多个字符串组合的富文本
    func combined(with other: [Any]) -> NSAttributedString {
        let result = NSMutableAttributedString(string: self)
        other.forEach { objc in
            if let v = objc as? String {
                result.append(NSAttributedString(string: v))
            }else if let v =  objc as? NSAttributedString {
                result.append(v)
            }
        }
        
        return result
    }
}

extension NSAttributedString {
    // 支持多个字符串组合的富文本
    func combined(with other: [Any]) -> NSAttributedString {
        let result = NSMutableAttributedString(attributedString: self)
        other.forEach { objc in
            if let v = objc as? String {
                result.append(NSAttributedString(string: v))
            }else if let v =  objc as? NSAttributedString {
                result.append(v)
            }
        }
        return result
    }
}

class AttributedStringBuilder {
    private var attributes: [NSAttributedString.Key: Any] = [:]
    private var string: String = ""
    
    init(_ string: String) {
        self.string = string
    }
    
    /// 设置字体
    @discardableResult
    func font(_ font: UIFont) -> Self {
        attributes[.font] = font
        return self
    }
    
    /// 设置文本颜色
    @discardableResult
    func color(_ color: UIColor) -> Self {
        attributes[.foregroundColor] = color
        return self
    }
    
    /// 设置背景颜色
    @discardableResult
    func backgroundColor(_ color: UIColor) -> Self {
        attributes[.backgroundColor] = color
        return self
    }
    
    /// 设置下划线
    @discardableResult
    func underline(_ style: NSUnderlineStyle = .single) -> Self {
        attributes[.underlineStyle] = style.rawValue
        return self
    }
    
    /// 设置删除线
    @discardableResult
    func strikethrough(_ style: NSUnderlineStyle = .single) -> Self {
        attributes[.strikethroughStyle] = style.rawValue
        return self
    }
    
    /// 设置段落样式
    @discardableResult
    func paragraphStyle(_ alignment: NSTextAlignment = .left, lineSpacing: CGFloat = 0) -> Self {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.alignment = alignment
        paragraphStyle.lineSpacing = lineSpacing
        attributes[.paragraphStyle] = paragraphStyle
        return self
    }
    
    /// 设置字符间距
    @discardableResult
    func kerning(_ value: CGFloat) -> Self {
        attributes[.kern] = value
        return self
    }
    
    /// 设置链接
    @discardableResult
    func link(_ url: URL) -> Self {
        attributes[.link] = url
        return self
    }
    
    /// 构建富文本
    func build() -> NSAttributedString {
        return NSAttributedString(string: string, attributes: attributes)
    }
}
