#include <assert.h>
#include "render/rendertarget.h"

#include "render/texturesmanager.h"
#include "render/texture2d.h"

#include "glad/glad.h"

void RenderTarget::setDefaultFramebuffer()
{
	glBindFramebuffer(GL_FRAMEBUFFER, 0);
}

RenderTarget::RenderTarget()
{
	m_framebuffer = -1;
}

RenderTarget::~RenderTarget()
{
	m_framebuffer = -1;
}

void RenderTarget::create(const char* name /*= nullptr*/)
{
	assert(g_texturesManager);
	
	////////////////////////
	// Create FBO
	
	// generate frame buffer
	glGenFramebuffers(1, &m_framebuffer);
	glBindFramebuffer(GL_FRAMEBUFFER, m_framebuffer);
}

void RenderTarget::destroy()
{
	GLint drawFboId;
	glGetIntegerv(GL_FRAMEBUFFER_BINDING, &drawFboId);

	if (drawFboId == (GLint)m_framebuffer)
		glBindFramebuffer(GL_FRAMEBUFFER, 0);
	glDeleteFramebuffers(1, &m_framebuffer);
}

void RenderTarget::finialize()
{
	if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
		assert(0 && "RenderTarget::finialize: failed to finialize framebuffer. Framebuffer is not complete");
	}
}

void RenderTarget::attachColorTexture(int slot, Texture2D* texture)
{
	assert(texture && "Failed to assing nullptr texture");
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + slot, GL_TEXTURE_2D, texture->GetHandle(), 0);
}

void RenderTarget::attachDepthTexture(Texture2D* texture)
{
	assert(texture && "Failed to assing nullptr texture");
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texture->GetHandle(), 0);
}
