package electrosphere.renderer.framebuffer;

import electrosphere.logger.LoggerInterface;
import java.util.concurrent.TimeUnit;
import org.lwjgl.opengl.GL30;
import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER;
import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER_COMPLETE;
import static org.lwjgl.opengl.GL30.glBindFramebuffer;
import static org.lwjgl.opengl.GL30.glCheckFramebufferStatus;
import static org.lwjgl.opengl.GL30.glDeleteFramebuffers;
import static org.lwjgl.opengl.GL30.glGenFramebuffers;

/**
 *
 * @author amaterasu
 */
public class Framebuffer {
    
    int framebufferPointer;
    int texturePointer;
    
    public Framebuffer(){
        framebufferPointer = glGenFramebuffers();
    }
    
    public void setTexturePointer(int texturePointer){
        this.texturePointer = texturePointer;
    }
    
    public int getTexturePointer(){
        return texturePointer;
    }
    
    public void bind(){
        glBindFramebuffer(GL_FRAMEBUFFER, framebufferPointer);
    }
    
    public boolean isComplete(){
        bind();
        return glCheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
    }
    
    public int getFramebufferPointer(){
        return framebufferPointer;
    }
    
    public void free(){
        glDeleteFramebuffers(framebufferPointer);
    }
    
    public void blockUntilCompiled(){
        while(glCheckFramebufferStatus(framebufferPointer) != GL_FRAMEBUFFER_COMPLETE){
            try {
                TimeUnit.MILLISECONDS.sleep(1);
            } catch (InterruptedException ex) {
                LoggerInterface.loggerEngine.ERROR("Failed to sleep in framebuffer blocker", ex);
            }
        }
    }
}
