#include <frostbite2D/graphics/render_texture.h>
#include <SDL2/SDL.h>
#include <algorithm>
#include <glad/glad.h>

namespace frostbite2D {

RenderTexture::~RenderTexture() {
  Reset();
}

bool RenderTexture::Init(int width, int height) {
  return Resize(width, height);
}

bool RenderTexture::Resize(int width, int height) {
  width = std::max(width, 1);
  height = std::max(height, 1);

  if (framebufferID_ != 0 && texture_ && width_ == width && height_ == height) {
    return true;
  }

  Reset();

  texture_ = Texture::createEmpty(width, height);
  if (!texture_) {
    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
                 "RenderTexture: failed to create color texture %dx%d",
                 width, height);
    return false;
  }

  glGenFramebuffers(1, &framebufferID_);
  glBindFramebuffer(GL_FRAMEBUFFER, framebufferID_);
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
                         texture_->getID(), 0);

  GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  glBindFramebuffer(GL_FRAMEBUFFER, 0);

  if (status != GL_FRAMEBUFFER_COMPLETE) {
    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
                 "RenderTexture: framebuffer incomplete (status=0x%x)",
                 static_cast<unsigned int>(status));
    Reset();
    return false;
  }

  width_ = width;
  height_ = height;
  return true;
}

void RenderTexture::Reset() {
  texture_.Reset();

  if (framebufferID_ != 0) {
    glDeleteFramebuffers(1, &framebufferID_);
    framebufferID_ = 0;
  }

  width_ = 0;
  height_ = 0;
}

} // namespace frostbite2D
