//
//  IBMacro.h
//  Focus
//
//  Created by Ivan Ablamskyi on 7/3/11.
//  Copyright 2011 Internet Investmets Group. All rights reserved.
//

// Define macosx 10.6 version
#ifndef MAC_OS_X_VERSION_10_6
#define MAC_OS_X_VERSION_10_6 1060
#endif

#ifndef NSAppKitVersionNumber10_6
#define NSAppKitVersionNumber10_6 1038
#endif

// Define macosx 10.7
#ifndef MAC_OS_X_VERSION_10_7 
#define MAC_OS_X_VERSION_10_7 1070
#endif

// Define macro for building under Lion
#define IS_LION MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7

// Defince conditions of runing OS X 10.7 for runtime

#define IB_IS_RUNNING_ON_MAVERIKS (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_8)
#define IB_IS_RUNNING_ON_LION (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_6)
#define IB_IS_RUNNING_ON_ML (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_7)

#define IB_SHOW_ACTIVATION_WINDOW_AND_RETURN_IF_APP_IS_NOT_ACTIVATED \
	IBDocumentController *dc = (IBDocumentController *)[NSApplication sharedApplication].delegate;\
	if (!dc.isAppActivated) {\
		[dc showActivationWindow:nil];\
		return;\
	}


// Sign of number
NS_INLINE CGFloat sign(CGFloat v) {
    return (v != 0) ? ABS(v)/v : 0.0f;
}

// If value is in interval then returns value, otherwise return proper interval bound
NS_INLINE CGFloat clamp(CGFloat value, CGFloat min, CGFloat max) {
    return (value > min) ? ((value < max) ? value : max) : min;
}

#include <mach/mach_init.h> 
#include <mach/task.h> 
#include <sys/time.h> 
#include <sys/resource.h> 
#include <stdint.h> 
#include <string.h> 
#include <unistd.h> 

NS_INLINE int64_t MemoryUsage() {     
	struct task_basic_info         info;     
	kern_return_t           rval = 0;     
	mach_port_t             task = mach_task_self();     
	mach_msg_type_number_t  tcnt = TASK_BASIC_INFO_COUNT;     
	task_info_t             tptr = (task_info_t) &info;  
	
	memset(&info, 0, sizeof(info));         
	
	rval = task_info(task, TASK_BASIC_INFO, tptr, &tcnt);     
	if (!(rval == KERN_SUCCESS)) return 0;         
	return info.resident_size; 
}

NS_INLINE NSColor* midRectColorOnCurrentScreen(NSRect rect) {
    CGDirectDisplayID displayID = CGMainDisplayID();
	
	CGRect displayBounds = CGDisplayBounds(displayID);
	
	// flip coordinates
	rect.origin.y = displayBounds.size.height - (rect.origin.y + rect.size.height);
	
	CGImageRef image = CGDisplayCreateImageForRect(displayID, NSRectToCGRect(rect));
    NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc] initWithCGImage:image];
    CGImageRelease(image);
	CGFloat midColorValue = 0.0;
	for (int i = 0; i < rect.size.width; i++) {
		for (int j = 0; j < rect.size.height; j++) {
			NSColor *color = [bitmap colorAtX:i y:j];
			midColorValue += (color.redComponent + color.greenComponent + color.blueComponent) / 3;
		}
	}
	midColorValue /= rect.size.width * rect.size.height;
    [bitmap release];
	return [NSColor colorWithDeviceWhite:midColorValue alpha:1.0];
}