//
//  matchempokerViewController.m
//  matchempoker
//
//  Created by jarnoh on 3/30/11.
//  Copyright 2011 peekpoke. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>

#import "matchempokerViewController.h"
#import "EAGLView.h"
#import <mach/mach.h>
#import <mach/mach_time.h>

#import "TileInterfaces.h"
#import "IOSGLRenderer.h"


IOSGLRenderer *renderer;
ITileGame *theGame;
uint64_t oldt, t;

@interface matchempokerViewController ()
@property (nonatomic, retain) EAGLContext *context;
@property (nonatomic, assign) CADisplayLink *displayLink;



@end

@implementation matchempokerViewController

@synthesize animating, context, displayLink;

- (void)awakeFromNib
{
    EAGLContext *aContext = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
    
    if (!aContext)
        NSLog(@"Failed to create ES context");
    else if (![EAGLContext setCurrentContext:aContext])
        NSLog(@"Failed to set ES context current");
    
	self.context = aContext;
	[aContext release];
	
    [(EAGLView *)self.view setContentScaleFactor:2.0f];
    [(EAGLView *)self.view setContext:context];
    [(EAGLView *)self.view setFramebuffer];
    
    
    int w=self.view.bounds.size.width;
    int h=self.view.bounds.size.height;
    
    NSLog(@"%d x %d", w, h);
    
    renderer=new IOSGLRenderer();
    //theGame=createTileGame(renderer, 0,0, 65536, 65536 * h/w);
    theGame=createTileGame(renderer,-2500,0,65536+5000, 65536*3/2+2500);

    renderer->setGame(theGame);
    
    animating = FALSE;
    animationFrameInterval = 1;
    self.displayLink = nil;
}

- (void)dealloc
{
    // TODO destroy resources 
    
    // Tear down context.
    if ([EAGLContext currentContext] == context)
        [EAGLContext setCurrentContext:nil];
    
    [context release];
    
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewWillAppear:(BOOL)animated
{
    [self startAnimation];

    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [self stopAnimation];
    
    [super viewWillDisappear:animated];
}

- (void)viewDidUnload
{
	[super viewDidUnload];
	
    // TODO destroy resources 

    // Tear down context.
    if ([EAGLContext currentContext] == context)
        [EAGLContext setCurrentContext:nil];
	self.context = nil;	
}

- (NSInteger)animationFrameInterval
{
    return animationFrameInterval;
}

- (void)setAnimationFrameInterval:(NSInteger)frameInterval
{
    /*
	 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 (frameInterval >= 1) {
        animationFrameInterval = frameInterval;
        
        if (animating) {
            [self stopAnimation];
            [self startAnimation];
        }
    }
}

- (void)startAnimation
{
    if (!animating) {
        CADisplayLink *aDisplayLink = [[UIScreen mainScreen] displayLinkWithTarget:self selector:@selector(drawFrame)];
        [aDisplayLink setFrameInterval:animationFrameInterval];
        [aDisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
        self.displayLink = aDisplayLink;
        
        animating = TRUE;
    }
}

- (void)stopAnimation
{
    if (animating) {
        [self.displayLink invalidate];
        self.displayLink = nil;
        animating = FALSE;
    }
}

- (void)drawFrame
{
    [(EAGLView *)self.view setFramebuffer];
    
//    glClearColor(0.5f, (rand()&255)/255.0f, 1.0f, 1.0f);
    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glDisable( GL_DEPTH_TEST );
    glEnable(GL_BLEND);
    glEnable(GL_TEXTURE_2D);

//    renderer->renderBackground(0);
    oldt=t;
    t=mach_absolute_time();
    uint64_t dt = t-oldt;
    if(oldt==0) dt=0;
    
    mach_timebase_info_data_t info;
    mach_timebase_info(&info);      
    
    dt *= info.numer;
    dt /= info.denom;
    dt *= 65536; 
    dt /= 1000000000; 
    
    theGame->run(dt);
    theGame->draw();
    
    [(EAGLView *)self.view presentFramebuffer];
}


-(void)click:(CGPoint)pt type:(eMOUSEEVENT)type
{
    int w=self.view.bounds.size.width;
    int h=self.view.bounds.size.height;

    int x=(pt.x*65536.0f/w);
    int y=(pt.y*65536.0f*1.5f/h); // TODO fixed 1.5 aspect ratio

    NSLog(@"click %d, %d, %d", x, y, type);
    
    theGame->click(x, y, type);
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"touchesBegan");
    [self click:[[touches anyObject] locationInView:nil] type:eMOUSEEVENT_BUTTONDOWN];
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"touchesMoved");
    [self click:[[touches anyObject] locationInView:nil] type:eMOUSEEVENT_MOUSEDRAG];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"touchesEnded");
    [self click:[[touches anyObject] locationInView:nil] type:eMOUSEEVENT_BUTTONUP];
}


@end
