/* Copyright (c) 2011 Artjom Popov */

#import "UIColor+Additions.h"


@implementation UIColor(Additions)

+ (UIColor *)colorWithString:(NSString *)str
{
	const char *ptr = str.UTF8String;
	const char *end = ptr + str.length;
	
    if(ptr < end && *ptr == '#') {
        unsigned int index = 0;
        UInt8 hexBuffer[6];
        
        ptr++; // Skip '#'
        
        while(ptr < end) {
            const char ch = *ptr;
            
			if(ch >= '0' && ch <= '9') hexBuffer[index] = ch - '0';
            else if(ch >= 'A' && ch <= 'F') hexBuffer[index] = ch - 'A' + 10;
            else if(ch >= 'a' && ch <= 'f') hexBuffer[index] = ch - 'a' + 10;
            else if(index != 3 && index != 6) return nil;
            else break;
            
            if(index >= 6) return nil;
            
            index++;
            ptr++;
        }
        
        if(index == 6) return [[[UIColor alloc] initWithRed:(16 * hexBuffer[0] + hexBuffer[1]) / 255.0F green:(16 * hexBuffer[2] + hexBuffer[3]) / 255.0F blue:(16 * hexBuffer[4] + hexBuffer[5]) / 255.0F alpha:1.0F] autorelease];
		if(index == 3) return [[[UIColor alloc] initWithRed:(16 * hexBuffer[0] + hexBuffer[0]) / 255.0F green:(16 * hexBuffer[1] + hexBuffer[1]) / 255.0F blue:(16 * hexBuffer[2] + hexBuffer[2]) / 255.0F alpha:1.0F] autorelease];
    }
    
    return nil;
}

+ (UIColor *)themeBackgroundColor
{
	return [UIColor groupTableViewBackgroundColor];
}

+ (UIColor *)themeButtonTextColor
{
	return [UIColor whiteColor];
}

+ (UIColor *)themeButtonTextShadowColor
{
	return [UIColor blackColor];
}

+ (UIColor *)themeGrayColor
{
	return [UIColor grayColor];
}

+ (UIColor *)themeRedColor
{
	return [UIColor redColor];
}

+ (UIColor *)themeGreenColor
{
	return [UIColor colorWithString:@"#4AA02C"];
}


- (UIColor *)colorWithValue:(CGFloat)value
{
	CGFloat components[4];
	
	if(CGColorGetNumberOfComponents(self.CGColor) == 2) {
		components[0] = CGColorGetComponents(self.CGColor)[0];
		components[1] = components[0];
		components[2] = components[0];
		components[3] = CGColorGetComponents(self.CGColor)[1];
	} else {
		memcpy(&(components[0]), CGColorGetComponents(self.CGColor), sizeof(CGFloat) * 4);
	}
	
	for(NSInteger i = 0; i < 3; i++) {
		components[i] = components[i] + value;
		if(components[i] < 0.0F) components[i] = 0.0F;
		if(components[i] > 1.0F) components[i] = 1.0F;
	}
	
	return [UIColor colorWithRed:components[0] green:components[1] blue:components[2] alpha:components[3]];
}

@end
