/* SimplyGL window system module for iOS */
/* mac-framework: -framework UIKit */

#include "config.h"

#ifdef USE_WSYS_MODULE_IOS

#include <assert.h>
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#include <OpenGLES/ES2/gl.h>
#include <OpenGLES/ES2/glext.h>

@interface SGLView : UIView {
@private
	BOOL active;
	BOOL use_disp_link;
	NSInteger frame_interval;
	id disp_link;
	NSTimer *anim_timer;
	EAGLContext *ctx;
	unsigned int fbo, rbuf_color, rbuf_depth;
}

@property (readonly, nonatomic, getter=isAnimating) BOOL active;
@property (nonatomic) NSInteger frame_interval;

-(void)start_anim;
-(void)stop_anim;
-(void)drawView: (id)sender;
@end

@interface SGLDelegate : NSObject <UIApplicationDelegate> {
	UIWindow *win;
	SGLView *view;
}

@property (nonatomic, retain) IBOutlet UIWindow *win;
@property (nonatomic, retain) IBOutlet SGLView *view;
@end



static int init(void);
static void shutdown(void);

/* video mode switching */
static int set_vidmode(int xsz, int ysz);
static int get_vidmode(int *xsz, int *ysz);

/* create/destroy windows */
static int create_window(int xsz, int ysz, unsigned int flags);
static void close_window(int wid);

/* window management */
static int set_active(int wid);
static int set_title(const char *str);
static void redisplay(void);
static void swap_buffers(void);

static int get_modifiers(void);

/* event handling and friends */
static void set_event(int idx, int enable);
static int process_events(void);


static struct wsys_module ws = {
	"ios", 0,
	init,
	shutdown,
	set_vidmode,
	get_vidmode,
	create_window,
	close_window,
	set_active,
	set_title,
	redisplay,
	swap_buffers,
	get_modifiers,
	set_event,
	process_events,
	0
};


void sgl_register_ios(void)
{
	sgl_register_module(&ws);
}


@implementation SGLView

@synthesize active;
@dynamic frame_interval;

+(Class)layerClass
{
	return [CAEAGLLayer class];
}

/*The EAGL view is stored in the nib file. When it's unarchived it's sent -initWithCoder: */
-(id)initWithCoder: (NSCoder*)coder
{
	if((self = [super initWithCoder: coder])) {
		/* Get the layer */
		CAEAGLLayer *layer = (CAEAGLLayer*)self.layer;

		/*self.contentScaleFactor = 2.0; */

		layer.opaque = TRUE;
		layer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
			[NSNumber numberWithBool: FALSE],
			kEAGLDrawablePropertyRetainedBacking, kEAGLColorFormatRGBA8,
			kEAGLDrawablePropertyColorFormat,
			nil];

		ctx = [[EAGLContext alloc] initWithAPI: kEAGLRenderingAPIOpenGLES2];
		if(!ctx || ![EAGLContext setCurrentContext: ctx]) {
			[self release];
			return nil;
		}

		/* initialize fbos etc... */
		glGenFramebuffers(1, &fbo);
		glBindFramebuffer(GL_FRAMEBUFFER, fbo);

		glGenRenderbuffers(1, &rbuf_color);
		glBindRenderbuffer(GL_RENDERBUFFER, rbuf_color);
		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbuf_color);

		glGenRenderbuffers(1, &rbuf_depth);
		glBindRenderbuffer(GL_RENDERBUFFER, rbuf_depth);
		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbuf_depth);
		assert(glGetError() == GL_NO_ERROR);

		active = FALSE;
		use_disp_link = FALSE;
		frame_interval = 1;
		disp_link = nil;
		anim_timer = nil;

		/* A system version of 3.1 or greater is required to use CADisplayLink. The NSTimer */
		/* class is used as fallback when it isn't available. */
		NSString *req_ver = @"3.1";
		NSString *cur_ver = [[UIDevice currentDevice] systemVersion];
		if([cur_ver compare: req_ver options: NSNumericSearch] != NSOrderedAscending) {
			use_disp_link = TRUE;
		}

		/*self.multipleTouchEnabled = 1; */

		/* TODO call user init ? */
	}

	return self;
}

-(void)drawView: (id)sender
{
	/* TODO call display */
}

-(void)layoutSubviews
{
	/* TODO call reshape */
	/* XXX originally call to renderer resizeFromLayer */
	/* XXX originally call to [self drawView: nil] */
}

-(void)setAnimationFrameInterval: (NSInteger)interval
{
	/* Frame interval defines how many display frames must pass
	 * between each time the display link fires. The display
	 * link will only fire 30 times a second when the frame
	 * internal is two on a display that refreshes 60 times a
	 * second. The default frame interval setting of one will
	 * fire 60 times a second when the display refreshes at 60
	 * times a second. A frame interval setting of less than
	 * one results in undefined behavior.
	 */
	if(interval >= 1) {
		frame_interval = frame_interval;

		if(active)
		{
			[self stop_anim];
			[self start_anim];
		}
	}
}

-(void)start_anim
{
	if(!active) {
		if(use_disp_link) {
			/* CADisplayLink is API new to iPhone SDK 3.1. Compiling against earlier versions will result in a warning, but can be dismissed
			 * if the system version runtime check for CADisplayLink exists in -initWithCoder:. The runtime check ensures this code will
			 * not be called in system versions earlier than 3.1.
			 */

			disp_link = [NSClassFromString(@"CADisplayLink") displayLinkWithTarget: self
				selector: @selector(drawView:)];
			[disp_link setFrameInterval: frame_interval];
			[disp_link addToRunLoop: [NSRunLoop currentRunLoop] forMode: NSDefaultRunLoopMode];
		} else {
			anim_timer = [NSTimer scheduledTimerWithTimeInterval: (NSTimeInterval)((1.0 / 60.0) * frame_interval)
				target: self selector: @selector(drawView:) userInfo: nil
				repeats: TRUE];
		}

		active = TRUE;
	}
}

- (void)stop_anim
{
	if(active) {
		if(use_disp_link) {
			[disp_link invalidate];
			disp_link = nil;
		} else {
			[anim_timer invalidate];
			anim_timer = nil;
		}

		active = FALSE;
	}
}

-(void)dealloc
{
	/* XXX originally [renderer release]; */
	[super dealloc];
}
@end

@implementation SGLDelegate

@synthesize win;
@synthesize view;

-(BOOL)application: (UIApplication*)app didFinishLaunchingWithOptions: (NSDictionary*)opt
{
	[view start_anim];
	return YES;
}

-(void)applicationWillResignActive: (UIApplication*)app
{
	[view stop_anim];
}

-(void)applicationDidBecomeActive: (UIApplication*)app
{
	[view start_anim];
}

-(void)applicationWillTerminate: (UIApplication*)app
{
	[view stop_anim];
}

-(void)dealloc
{
	[win release];
	[view release];
	[super dealloc];
}
@end



static int init(void)
{
	return -1;
}

static void shutdown(void)
{
}

/* video mode switching */
static int set_vidmode(int xsz, int ysz)
{
	return -1;
}

static int get_vidmode(int *xsz, int *ysz)
{
	return -1;
}

/* create/destroy windows */
static int create_window(int xsz, int ysz, unsigned int flags)
{
	return -1;
}

static void close_window(int wid)
{
}

/* window management */
static int set_active(int wid)
{
	return -1;
}

static int set_title(const char *str)
{
	return -1;
}

static void redisplay(void)
{
}

static void swap_buffers(void)
{
}

static int get_modifiers(void)
{
	return 0;
}

/* event handling and friends */
static void set_event(int idx, int enable)
{
}

static int process_events(void)
{
	return -1;
}





/* only compile the following if we're building in xcode and we
 * don't have generated modules.c file
 */
#ifdef XCODE_BUILD
@interface sgl : NSObject
/* XXX no need for init yet... */
@end

@implementation sgl

- (id)init
{
    self = [super init];
    if(self) {
        /* XXX Initialization code here. */
    }
    return self;
}

@end

void sgl_modules_init(void)
{
	sgl_register_uikit();
}

#endif	/* XCODE_BUILD */


#else
int sgl_wsys_ios_silence_the_fucking_empty_file_warnings;
#endif	/* USE_WSYS_MODULE_IOS */
