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

import UIKit

extension UIColor {
    /// 返回一个随机颜色
    static var random: UIColor {
        return UIColor(
            red: CGFloat.random(in: 0...1),
            green: CGFloat.random(in: 0...1),
            blue: CGFloat.random(in: 0...1),
            alpha: 1.0
        )
    }
    
    static func fromHex(_ hex: String, alpha: CGFloat = 1.0) -> UIColor {
        var cleanedHex = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
        
        // Remove leading "#" if present
        if cleanedHex.hasPrefix("#") {
            cleanedHex.removeFirst()
        }
        
        // Ensure valid hex length
        guard cleanedHex.count == 6 else {
            return UIColor.clear // Return clear color for invalid input
        }
        
        // Extract RGB components
        var rgbValue: UInt64 = 0
        Scanner(string: cleanedHex).scanHexInt64(&rgbValue)
        
        let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
        let green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0
        let blue = CGFloat(rgbValue & 0x0000FF) / 255.0
        
        return UIColor(red: red, green: green, blue: blue, alpha: alpha)
    }

}
extension UIColor {
    /// 调整颜色的亮度和饱和度
    /// - Parameters:
    ///   - brightnessFactor: 亮度因子（范围 0.0 - 1.0, 0 表示完全黑暗, 1 表示原始亮度）
    ///   - saturationFactor: 饱和度因子（范围 0.0 - 1.0, 0 表示无饱和度, 1 表示原始饱和度）
    /// - Returns: 调整后的颜色
    func adjusted(brightness brightnessFactor: CGFloat = 1.0, saturation saturationFactor: CGFloat = 1.0) -> UIColor {
        var hue: CGFloat = 0
        var saturation: CGFloat = 0
        var brightness: CGFloat = 0
        var alpha: CGFloat = 0
        
        if self.getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) {
            // 根据 factor 计算调整后的亮度和饱和度
            let adjustedBrightness = brightness * brightnessFactor
            let adjustedSaturation = saturation * saturationFactor
            return UIColor(hue: hue, saturation: adjustedSaturation, brightness: adjustedBrightness, alpha: alpha)
        }
        return self
    }
    
    /// 获取颜色的亮度
    var brightness: CGFloat? {
        var brightness: CGFloat = 0
        if self.getHue(nil, saturation: nil, brightness: &brightness, alpha: nil) {
            return brightness
        }
        return nil
    }
    
    /// 获取颜色的饱和度
    var saturation: CGFloat? {
        var saturation: CGFloat = 0
        if self.getHue(nil, saturation: &saturation, brightness: nil, alpha: nil) {
            return saturation
        }
        return nil
    }
}
