//
//  UIFont+Ex.swift
//  TSLiveWallpaper
//
//  Created by 100Years on 2024/12/20.
//

typealias FontName = String

extension FontName {
    static let PingFangSC           = "PingFangSC"
}


extension UIFont {
    class func font(name: FontName = .PingFangSC, size: CGFloat, weight: UIFont.Weight = .regular) -> UIFont {
        guard !name.isEmpty,
                let _ = UIFont(name: name, size: size) else {
            return UIFont.systemFont(ofSize: size, weight: weight)
        }
        var finalFontName = name
        
        let fontNames = UIFont.fontNames(forFamilyName: name)
        switch weight {
        case .light://细体 300
            if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-light") || $0.lowercased().hasSuffix("_light") }) {
                finalFontName = aName
            }
        case .medium://中黑体 500
            if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-medium") || $0.lowercased().hasSuffix("_medium") }) {
                finalFontName = aName
            }
        case .bold:// 粗体 700
            if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-bold") || $0.lowercased().hasSuffix("_bold") }) {
                finalFontName = aName
            }
        case .semibold://半粗体 600
            if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-semibold") || $0.lowercased().hasSuffix("_semibold") }) {
                finalFontName = aName
            }
        case .heavy: //粗黑体 800
            if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-heavy") || $0.lowercased().hasSuffix("_heavy") }) {
                finalFontName = aName
            }
        case .black: // 黑体 900
            if let aName = fontNames.first(where: { $0.lowercased().hasSuffix("-black") || $0.lowercased().hasSuffix("_black") }) {
                finalFontName = aName
            }
        default:
            break
        }
        
        return UIFont(name: finalFontName, size: size)!
    }
}
extension UIFont {
    
    /// 返回该字体下，对应字符的宽度
    /// - Parameter word: 字符
    /// - Returns: 宽度
    func widthForWord(_ word: String) -> CGFloat {
        
        let sizeWidth = (word as NSString).size(withAttributes: [.font: self]).width
        return sizeWidth//.rounded(.up)
    }
}
