/*
 * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
 */

#import "GlassOffscreen.h"

#import "GlassFrameBufferObject.h"
//#import "GlassPBuffer.h"

@implementation GlassOffscreen

- (id)init
{
    self = [super init];
    if (self != nil)
    {
        self->_lock = [[NSRecursiveLock alloc] init];
        
        self->_backgroundR = 1.0f;
        self->_backgroundG = 1.0f;
        self->_backgroundB = 1.0f;
        self->_backgroundA = 1.0f;
        
        self->_offscreen = [[GlassFrameBufferObject alloc] init];
        if (self->_offscreen == nil)
        {
            // TODO: implement PBuffer if needed
            //self->_offscreen = [[GlassPBuffer alloc] init];
        }
    }
    return self;
}

- (void)dealloc
{
    [self->_lock release];
    self->_lock = nil;
    
    [super dealloc];
}

- (void)setBackgroundColor:(NSColor*)color
{
    self->_backgroundR = [color redComponent];
    self->_backgroundG = [color greenComponent];
    self->_backgroundB = [color blueComponent];
    self->_backgroundA = [color alphaComponent];
}

- (void)lock
{
    [self->_lock lock];
}

- (void)unlock;
{
    [self->_lock unlock];
}

- (NSSize)size
{
    return [self->_offscreen size];
}

- (void)bindForWidth:(NSUInteger)width andHeight:(NSUInteger)height
{
    [self lock];
    {
        [self->_offscreen bindForWidth:width andHeight:height];
    }
    // will be unlocked later by [GlassOffscreen unbind]
}

- (void)unbind
{
    // already locked eariler by [GlassOffscreen bindForWidth:andHeight];
    {
        [self->_offscreen unbind];
    }
    [self unlock];
}

- (void)blit
{
    [self lock];
    {
        NSSize size = [self->_offscreen size];
        [self blitForWidth:size.width andHeight:size.height];
    }
    [self unlock];
}

- (void)blitForWidth:(NSUInteger)width andHeight:(NSUInteger)height
{
    [self lock];
    {
        glClearColor(self->_backgroundR, self->_backgroundG, self->_backgroundB, self->_backgroundA);
        glClear(GL_COLOR_BUFFER_BIT);
        glFlush();
        
        [self->_offscreen blitForWidth:width andHeight:height];
    }
    [self unlock];
}

@end
