//
//  KMAdvertisementColorConversion.swift
//  KMAdvertisement
//
//  Created by lizhe on 2022/11/30.
//

#if os(OSX)
    import AppKit
#elseif os(iOS)
    import UIKit
#endif


extension NSColor {
    
    convenience init(hex: String) {
        var hexString = hex
        if hex.starts(with: "#") {
            hexString = String(hex.dropFirst())
        }
        if let ui64 = UInt64(hexString, radix: 16) {
            self.init(hex: Int(ui64))
        } else {
            self.init(hex: 0)  // <--- black
        }
        // or using ternaries as requested
        // let hexString = hex.starts(with: "#") ? String(hex.dropFirst()) : hex
        // let ui64 = UInt64(hexString, radix: 16)
        // self.init(hex: ui64 != nil ? Int(ui64!) : 0)
    }
        
        convenience init(hex: Int) {
            let components = (
                R: CGFloat((hex >> 16) & 0xff) / 255,
                G: CGFloat((hex >> 08) & 0xff) / 255,
                B: CGFloat((hex >> 00) & 0xff) / 255
            )
            self.init(red: components.R, green: components.G, blue: components.B, alpha: 1)
        }

    func toHex(alpha: Bool = false) -> String? {
        guard let components = cgColor.components, components.count >= 3 else {
            return nil
        }
        
        let r = Float(components[0])
        let g = Float(components[1])
        let b = Float(components[2])
        var a = Float(1.0)
        
        if components.count >= 4 {
            a = Float(components[3])
        }
        
        if alpha {
            return String(format: "%02lX%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255), lroundf(a * 255))
        } else {
            return String(format: "%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255))
        }
    }
}
