/*
 * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
 */

// http://developer.apple.com/documentation/graphicsimaging/Conceptual/drawingwithquartz2d/dq_images/dq_images.html
// http://developer.apple.com/documentation/graphicsimaging/Conceptual/drawingwithquartz2d/dq_data_mgr/dq_data_mgr.html

// http://developer.apple.com/documentation/graphicsimaging/reference/CGImage/Reference/reference.html
// http://developer.apple.com/documentation/graphicsimaging/reference/CGDataProvider/Reference/reference.html
// http://developer.apple.com/documentation/graphicsimaging/Reference/CGImageSource/Reference/reference.html

#import <Cocoa/Cocoa.h>

#import "common.h"
#import "com_sun_rain_graphics_Image.h"

static jclass jImageClass = NULL;

/*
 * Class:     com_sun_rain_graphics_Image
 * Method:    _initIDs
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_com_sun_rain_graphics_Image__1initIDs
  (JNIEnv *env, jclass jClass)
{
    jImageClass = (*env)->NewGlobalRef(env, (*env)->FindClass(env, "com/sun/rain/graphics/Image"));
}

/*
 * Class:     com_sun_rain_graphics_Image
 * Method:    _createImage
 * Signature: (IILjava/nio/ByteBuffer;)V
 */
JNIEXPORT void JNICALL Java_com_sun_rain_graphics_Image__1createImage
  (JNIEnv *env, jobject jimage, jint jwidth, jint jheight, jobject jpixels)
{
    off_t pixelsLength = (*env)->GetDirectBufferCapacity(env, jpixels);
    void *pixels = (*env)->GetDirectBufferAddress(env, jpixels);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, pixels, pixelsLength, NULL);
    CGImageRef cgImage = CGImageCreate(jwidth, jheight, 8, 32, 4*jwidth, colorSpace, kCGImageAlphaPremultipliedFirst|kCGBitmapByteOrder32Host, provider, NULL, 1, kCGRenderingIntentDefault);
    CGDataProviderRelease(provider);
    CGColorSpaceRelease(colorSpace);
    
    (*env)->SetLongField(env, jimage, (*env)->GetFieldID(env, jImageClass, "ptr", "J"), ptr_to_jlong(cgImage));
}

