//
//  Color+Extensions.swift
//  PadelClub
//
//  Created by Razmig Sarkissian on 27/03/2024.
//

import SwiftUI
import UIKit

extension Color {
    
    func variation(withHueOffset hueOffset: Double = 0, saturationFactor: Double = 0.4, brightnessFactor: Double = 0.8, opacity: Double = 0.5) -> Color {
        var hue: CGFloat = 0
        var saturation: CGFloat = 0
        var brightness: CGFloat = 0
        var alpha: CGFloat = 0
        
        UIColor(self).getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha)
        
        // Apply adjustments
        hue += CGFloat(hueOffset)
        saturation *= CGFloat(saturationFactor)
        brightness *= CGFloat(brightnessFactor)
        alpha *= CGFloat(opacity)
        
        // Clamp values
        hue = max(0, min(hue, 1))
        saturation = max(0, min(saturation, 1))
        brightness = max(0, min(brightness, 1))
        alpha = max(0, min(alpha, 1))
        
        return Color(hue: Double(hue), saturation: Double(saturation), brightness: Double(brightness), opacity: Double(alpha))
    }
    
}

extension UIColor {
    /// Initialises NSColor from a hexadecimal string. Color is clear if string is invalid.
    /// - Parameter fromHex: supported formats are "#RGB", "#RGBA", "#RRGGBB", "#RRGGBBAA", with or without the # character
    public convenience init(fromHex:String) {
        var r = 0, g = 0, b = 0, a = 255
        let offset = fromHex.hasPrefix("#") ? 1 : 0
        let ch = fromHex.map{$0}
        switch(ch.count - offset) {
        case 8:
            a = 16 * (ch[offset+6].hexDigitValue ?? 0) + (ch[offset+7].hexDigitValue ?? 0)
            fallthrough
        case 6:
            r = 16 * (ch[offset+0].hexDigitValue ?? 0) + (ch[offset+1].hexDigitValue ?? 0)
            g = 16 * (ch[offset+2].hexDigitValue ?? 0) + (ch[offset+3].hexDigitValue ?? 0)
            b = 16 * (ch[offset+4].hexDigitValue ?? 0) + (ch[offset+5].hexDigitValue ?? 0)
            break
        case 4:
            a = 16 * (ch[offset+3].hexDigitValue ?? 0) + (ch[offset+3].hexDigitValue ?? 0)
            fallthrough
        case 3:  // Three digit #0D3 is the same as six digit #00DD33
            r = 16 * (ch[offset+0].hexDigitValue ?? 0) + (ch[offset+0].hexDigitValue ?? 0)
            g = 16 * (ch[offset+1].hexDigitValue ?? 0) + (ch[offset+1].hexDigitValue ?? 0)
            b = 16 * (ch[offset+2].hexDigitValue ?? 0) + (ch[offset+2].hexDigitValue ?? 0)
            break
        default:
            a = 0
            break
        }
        self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: CGFloat(a)/255)
        
    }
}
