#import <AppKit/NSOpenGL.h>
#import <AppKit/NSWindow.h>
#include <stdlib.h>
#include "cocoaglcontext.h"

NSOpenGLPixelFormat *get_native_pixel_format(CocoaPixelFormat *);
NSWindow *get_native_window(CocoaWindow *);

struct _CocoaGLContext
{
	NSOpenGLContext *context;
};

CocoaGLContext *create_gl_context(CocoaPixelFormat *format)
{
	NSOpenGLContext *ctx = [NSOpenGLContext alloc];
	ctx = [ctx initWithFormat:get_native_pixel_format(format) shareContext:nil];
	if(!ctx)
		return NULL;

	CocoaGLContext *wrapper = (CocoaGLContext *)malloc(sizeof(CocoaGLContext));
	wrapper->context = ctx;
	return wrapper;
}

void destroy_gl_context(CocoaGLContext *context)
{
	[context->context release];
	free(context);
}

void attach_gl_context_to_window(CocoaGLContext *context, CocoaWindow *window)
{
	NSWindow *nswindow = get_native_window(window);
	[context->context setView:[nswindow contentView]];
}

void make_gl_context_current(CocoaGLContext *context)
{
	[context->context makeCurrentContext];
}

void flush_gl_buffer(CocoaGLContext *context)
{
	[context->context flushBuffer];
}
