#import <AppKit/NSWindow.h>
#import <CoreFoundation/CFArray.h>
#include "cocoadisplay.h"
#include "cocoawindow.h"

@interface WindowDelegate: NSObject <NSWindowDelegate>

- (BOOL)windowShouldClose:(id)sender;

@end

struct _CocoaWindow
{
	CocoaDisplay *display;
	__strong NSWindow *window;
	__strong WindowDelegate *delegate;
	NSUInteger style;
};

CFMutableDictionaryRef windows = NULL;

CocoaWindow *create_window(CocoaDisplay *display, unsigned width, unsigned height, bool fullscreen, bool resizable)
{
	NSRect rect = NSMakeRect(0, 0, width, height);
	NSUInteger style = NSTitledWindowMask|NSClosableWindowMask;
	if(resizable)
		style |= NSResizableWindowMask;
	NSWindow *window = [NSWindow alloc];
	window = [window initWithContentRect:rect styleMask:style backing:NSBackingStoreBuffered defer:NO];
	[window setAcceptsMouseMovedEvents:YES];

	(void)fullscreen;

	CocoaWindow *wrapper = (CocoaWindow *)malloc(sizeof(CocoaWindow));
	wrapper->display = display;
	wrapper->window = window;
	wrapper->style = style;

	wrapper->delegate = [[WindowDelegate alloc] init];
	[window setDelegate:wrapper->delegate];

	if(!windows)
		windows = CFDictionaryCreateMutable(NULL, 0, NULL, NULL);
	CFDictionaryAddValue(windows, window, wrapper);

	return wrapper;
}

void destroy_window(CocoaWindow *window)
{
	CFDictionaryRemoveValue(windows, window->window);
	if(!CFDictionaryGetCount(windows))
	{
		CFRelease(windows);
		windows = NULL;
	}

	[window->window release];
	[window->delegate release];
	free(window);
}

NSWindow *get_native_window(CocoaWindow *window)
{
	return window->window;
}

CocoaWindow *lookup_window(NSWindow *window)
{
	return (CocoaWindow *)CFDictionaryGetValue(windows, window);
}

void set_window_title(CocoaWindow *window, const char *title)
{
	[window->window setTitle:[NSString stringWithCString:title encoding:NSUTF8StringEncoding]];
}

void set_window_size(CocoaWindow *window, unsigned width, unsigned height)
{
	NSRect rect = NSMakeRect(0, 0, width, height);
	rect = [NSWindow frameRectForContentRect:rect styleMask:window->style];
	[window->window setFrame:rect display:YES];
}

void show_window(CocoaWindow *window)
{
	[window->window makeKeyAndOrderFront:nil];
	[NSApp activateIgnoringOtherApps:NO];
}

void hide_window(CocoaWindow *window)
{
	(void)window;
}

@implementation WindowDelegate

- (BOOL)windowShouldClose:(id)sender
{
	CocoaWindow *window = lookup_window((NSWindow *)sender);
	if(window)
	{
		CocoaEvent event;
		event.any.type = WINDOW_CLOSED;
		event.any.window = window;
		queue_event(window->display, &event);
		return NO;
	}
	return YES;
}

@end
