//
//  NSColor+HWMExtension.m
//  HWMUISDKNativeDemo
//
//  Created by guomeng on 2020/10/24.
//  Copyright © 2020 Huawei Technologies Co. Ltd. All rights reserved.
//

#import "NSColor+HWMExtension.h"

@implementation NSColor (HWMExtension)

+ (NSColor *)colorWithRGB:(uint32_t)rgbValue
{
    float red = ((rgbValue & 0xFF0000) >> 16) / 255.0;
    float green = ((rgbValue & 0x00FF00) >> 8) / 255.0;
    float blue = ((rgbValue & 0x0000FF)) / 255.0;
    return [NSColor colorWithRed:red green:green blue:blue alpha:1.0];
}

+ (NSColor *)colorWithRGB:(uint32_t)rgbValue alpha:(CGFloat)alpha
{
    float red = ((rgbValue & 0xFF0000) >> 16) / 255.0;
    float green = ((rgbValue & 0x00FF00) >> 8) / 255.0;
    float blue = ((rgbValue & 0x0000FF)) / 255.0;
    return [NSColor colorWithRed:red green:green blue:blue alpha:alpha];
}

+ (NSColor *)colorWithRGBA:(uint32_t)rgbaValue
{
    float alpha = ((rgbaValue & 0xFF000000) >> 24) / 255.0;
    float red = ((rgbaValue & 0x00FF0000) >> 16) / 255.0;
    float green = ((rgbaValue & 0x0000FF00) >> 8) / 255.0;
    float blue = (rgbaValue & 0x000000FF) / 255.0;
    return [NSColor colorWithRed:red green:green blue:blue alpha:alpha];
}

+ (NSColor *)colorWithR:(float)r g:(float)g b:(float)b
{
    return [NSColor colorWithRed:r / 255.0 green:g / 255.0 blue:b / 255.0 alpha:1];
}

+ (NSColor *)randomColor {
    return [self colorWithR:arc4random() % 255 g:arc4random() % 255 b:arc4random() % 255];
}

+ (NSColor *)colorWithHexString:(NSString *)hexString {
    /// 移除字符串前缀
    NSString *cleanHexStr = [hexString stringByReplacingOccurrencesOfString:@"#" withString:@""];
    /// 校验字符串长度
    if (cleanHexStr.length != 6 && cleanHexStr.length != 8) {
        return nil;
    }
    /// 正则匹配字符串是否十六进制
    NSString *regexPattern = @"^[0-9A-Fa-f]+$";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexPattern options:NSRegularExpressionCaseInsensitive error:nil];
    NSTextCheckingResult *result = [regex firstMatchInString:cleanHexStr options:0 range:NSMakeRange(0, cleanHexStr.length)];
    if (!result) {
        return nil;
    }
    /// 解析十六进制
    unsigned int hexValue;
    [[NSScanner scannerWithString:cleanHexStr] scanHexInt:&hexValue];
    /// 创建Color
    BOOL hasAlpha = cleanHexStr.length == 8;
    float alpha = hasAlpha ? ((hexValue & 0xFF000000) >> 24) / 255.0 : 1.0;
    float red = ((hexValue & (hasAlpha ? 0xFF0000 : 0x00FF0000)) >> 16) / 255.0;
    float green = ((hexValue & (hasAlpha ? 0x00FF00 : 0x0000FF00)) >> 8) / 255.0;
    float blue = ((hexValue & (hasAlpha ? 0x0000FF : 0x000000FF))) / 255.0;
    return [NSColor colorWithRed:red green:green blue:blue alpha:alpha];
}

@end
