//
//  UIImage+UIImageAverageColorAddition.m
//  AvgColor
//
//  Created by nikolai on 28.08.12.
//  Copyright (c) 2012 Savoy Software. All rights reserved.
//

#import "UIImage+AverageColorAddition.h"

@implementation UIImage (UIImageAverageColorAddition)

- (UIColor *)averageColor {
    return [self averageColorInFrame:CGRectMake(0, 0, self.size.width * self.scale, self.size.height * self.scale)];
}

- (UIColor *)averageColorInFrame:(CGRect)frame
{
	if (!self)
		return nil;
    CGImageRef rawImageRef = [self CGImage];

    // This function returns the raw pixel values
	CFDataRef data = CGDataProviderCopyData(CGImageGetDataProvider(rawImageRef));
    const UInt8 *rawPixelData = CFDataGetBytePtr(data);
    NSUInteger imageHeight = frame.origin.y + frame.size.height;
    NSUInteger imageWidth  = frame.origin.x + frame.size.width;
    NSUInteger bytesPerRow = CGImageGetBytesPerRow(rawImageRef);
	NSUInteger stride = CGImageGetBitsPerPixel(rawImageRef) / 8;

    // Here I sort the R,G,B, values and get the average over the whole image
    unsigned int red   = 0;
    unsigned int green = 0;
    unsigned int blue  = 0;

	for (int row = frame.origin.y; row < imageHeight; row++) {
		const UInt8 *rowPtr = rawPixelData + bytesPerRow * row;
		for (int column = frame.origin.x; column < imageWidth; column++) {
            red    += rowPtr[0];
            green  += rowPtr[1];
            blue   += rowPtr[2];
			rowPtr += stride;

        }
    }
	CFRelease(data);

	CGFloat f = 1.0f / (255.0f * frame.size.width * frame.size.height);
	return [UIColor colorWithRed:f * red  green:f * green blue:f * blue alpha:1];
}

- (UIColor *)mergedColor
{
	CGSize size = {1, 1};
	UIGraphicsBeginImageContext(size);
	CGContextRef ctx = UIGraphicsGetCurrentContext();
	CGContextSetInterpolationQuality(ctx, kCGInterpolationMedium);
	[self drawInRect:(CGRect){.size = size} blendMode:kCGBlendModeCopy alpha:1];
	uint8_t* data = (uint8_t*)CGBitmapContextGetData(ctx);
	UIColor *color = [UIColor colorWithRed:data[2] / 255.0f
									 green:data[1] / 255.0f
									  blue:data[0] / 255.0f
									 alpha:1];
	UIGraphicsEndImageContext();
	return color;
}

@end

@implementation UIColor (LightCheck)

- (BOOL)isColorLight {
    CGFloat white = 0;
    [self getWhite:&white alpha:nil];
    return (white >= .7);
}

@end
