//
//  UIColor+Hexadecimal.swift
//  react-native-firework-sdk
//
//  Created by Jeff Zheng on 2021/12/22.
//

import UIKit

extension String {
    func uicolor() -> UIColor? {
        var hex = self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()

        guard matchHexColorWithLength(hex) else {
            return nil
        }

        if hex.hasPrefix("0X") {
            hex = String(hex[hex.index(hex.startIndex, offsetBy: 2)...])
        } else if hex.hasPrefix("#") {
            hex = String(hex[hex.index(hex.startIndex, offsetBy: 1)...])
        }

        if hex.count == 3 {
            hex = convertToDoubleChar(from: hex)
            hex += "FF"
        }

        if hex.count == 4 {
            hex = convertToDoubleChar(from: hex)
        }

        if hex.count == 6 {
            hex += "FF"
        }

        var rgbaValue: UInt64 = 0
        Scanner(string: hex).scanHexInt64(&rgbaValue)

        let red = CGFloat((rgbaValue & 0xFF000000) >> 24) / 255.0
        let green = CGFloat((rgbaValue & 0x00FF0000) >> 16) / 255.0
        let blue = CGFloat((rgbaValue & 0x0000FF00) >> 8) / 255.0
        let alpha = CGFloat(rgbaValue & 0x000000FF) / 255.0

        return UIColor(red: red, green: green, blue: blue, alpha: alpha)

    }

    private func convertToDoubleChar(from input: String) -> String {
        var result = ""

        for char in input {
            let repeatedChar = String(repeating: char, count: 2)
            result += repeatedChar
        }

        return result
    }

    private func matchHexColorWithLength(_ input: String) -> Bool {
        do {
            let pattern = "^(0X|#)?([0-9A-Fa-f]{3}|[0-9A-Fa-f]{4}|[0-9A-Fa-f]{6}|[0-9A-Fa-f]{8})$"
            let regex = try NSRegularExpression(pattern: pattern)
            let range = NSRange(location: 0, length: input.utf16.count)
            let matches = regex.matches(in: input, range: range)

            return matches.count > 0
        } catch {
            return false
        }
    }
}
