#import <AppKit/NSEvent.h>
#import <AppKit/NSWindow.h>
#import <Foundation/NSString.h>
#include "cocoaevent.h"

NSWindow *get_native_window(CocoaWindow *);
CocoaWindow *lookup_window(NSWindow *);

CocoaWindow *last_window = 0;

void convert_event(NSEvent *ev, CocoaEvent *cev)
{
	NSEventType type = [ev type];
	cev->any.type = (CocoaEventType)type;

	NSWindow *window = [ev window];
	if(window)
	{
		cev->any.window = lookup_window([ev window]);
		last_window = cev->any.window;
	}

	if(type==NSLeftMouseDown || type==NSLeftMouseUp)
	{
		cev->button.button = 1;
		cev->button.state = (type==NSLeftMouseDown);
	}
	else if(type==NSRightMouseDown || type==NSRightMouseUp)
	{
		cev->button.button = 3;
		cev->button.state = (type==NSRightMouseDown);
	}
	else if(type==NSOtherMouseDown || type==NSOtherMouseUp)
	{
		cev->button.button = [ev buttonNumber];
		cev->button.state = (type==NSOtherMouseDown);
	}
	else if(type==NSMouseMoved)
	{
		NSPoint pt = [ev locationInWindow];
		if(!window && last_window)
		{
			/* If the pointer leaves the window, any subsequent MouseMoved events
			are reported to a null window until the window is clicked. */
			window = get_native_window(last_window);
			pt = [window convertScreenToBase:pt];
			cev->any.window = last_window;
		}
		cev->motion.x = pt.x;
		cev->motion.y = pt.y;
	}
	else if(type==NSKeyDown)
	{
		NSString *chars = [[ev charactersIgnoringModifiers] uppercaseString];
		if([chars length]==1)
			cev->key.key = [chars characterAtIndex:0];

		chars = [ev characters];
		if([chars length]==1)
			cev->key.character = [chars characterAtIndex:0];
	}
}
