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

import UIKit

extension UIColor {

    convenience init(hex:UInt32 = 0xFFFFFF , alpha:Double = 1) {
        let red = Double((hex & 0xFF0000) >> 16) / 255.0
        let green = Double((hex & 0xFF00) >> 8) / 255.0
        let blue = Double((hex & 0xFF)) / 255.0
        self.init(red: red, green: green, blue: blue, alpha: alpha)
    }
    
    convenience init(with Hex:String = "#FFFFFF" , alpha:Double = 1) {
        var str = Hex.lowercased()
        if (str.hasPrefix("#") && str.count == 7) || (str.hasPrefix("0x") && str.count == 8) {
            if str.hasPrefix("#") {
                str = String(str[str.index(str.startIndex, offsetBy: 1)...])
            }else if str.hasPrefix("0x"){
                str = String(str[str.index(str.startIndex, offsetBy: 2)...])
            }
            var hexInt:UInt64 = 0
            Scanner(string: str).scanHexInt64(&hexInt)
            let red = Double((hexInt & 0xFF0000) >> 16) / 255.0
            let green = Double((hexInt & 0xFF00) >> 8) / 255.0
            let blue = Double((hexInt & 0xFF)) / 255.0
            self.init(red: red, green: green, blue: blue, alpha: alpha)
        }else{
            self.init(red: 1, green: 1, blue: 1, alpha: 0)
        }
    }
    
    public func generate(_ size:CGSize = CGSize(width: 1, height: 1),
                         _ cornerRadius:CGFloat = 0) -> UIImage? {
        let rect = CGRect(origin: .zero, size: size)
        UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        if cornerRadius > 0 {
            let path = UIBezierPath(roundedRect: rect, cornerRadius: cornerRadius/2.0)
            path.addClip()
            context.addPath(path.cgPath)
        }
        context.setFillColor(self.cgColor)
        context.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}
