//
//  LLQ_UIColorEx.swift
//  SnapVPN
//
//  Created by FastKey on 2020/12/21.
//

import UIKit

extension UIColor {

    public convenience init(_ value: Int, alpha: CGFloat = 1.0) {

        let red = CGFloat(value >> 16 & 0xff)
        let green = CGFloat(value >> 8 & 0xff)
        let black = CGFloat(value & 0xff)

        let color = UIColor(red: red/255.0, green: green/255.0, blue: black/255.0, alpha: alpha)

        self.init(cgColor: color.cgColor)
    }

    public convenience init?(hexString: String?, alpha: CGFloat? = 1) {

        guard let hexString = hexString else {
            return nil
        }

        let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
        var int = UInt32()
        Scanner(string: hex).scanHexInt32(&int)
        let a, r, g, b: UInt32
        switch hex.count {
        case 3: // RGB (12-bit)
            (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
        case 6: // RGB (24-bit)
            (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
        case 8: // ARGB (32-bit)
            (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
        default:
            (a, r, g, b) = (255, 0, 0, 0)
        }
        if alpha ?? 1 != 1.0 {
            self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: alpha ?? 1)
        } else {
            self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
        }
    }
    
}
