using OpenTK.Graphics.OpenGL;

namespace Engine.Graphics.Framebuffer;

public class Renderbuffer : OpenGlObject, IFramebufferAttachment
{
  public int Width { get; private set; }
  public int Height { get; private set; }

  private readonly RenderbufferStorage _format;

  public Renderbuffer(int parWidth, int parHeight, RenderbufferStorage parFormat)
  {
    Width = parWidth;
    Height = parHeight;
    _format = parFormat;

    GL.CreateRenderbuffers(1, out int handle);
    Handle = handle;

    GL.NamedRenderbufferStorage(Handle, _format, Width, Height);
  }

  public void Resize(int parWidth, int parHeight)
  {
    if (Width == parWidth && Height == parHeight)
    {
      return;
    }

    Width = parWidth;
    Height = parHeight;

    GL.NamedRenderbufferStorage(Handle, _format, Width, Height);
  }

  public void Attach(Framebuffer parFramebuffer, FramebufferAttachment parAttachment)
  {
    GL.NamedFramebufferRenderbuffer(parFramebuffer.Handle, parAttachment, RenderbufferTarget.Renderbuffer, Handle);
  }

  internal override void Bind()
  {
    GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, Handle);
  }

  internal override void Unbind()
  {
    GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, 0);
  }

  protected override void Destroy()
  {
    GL.DeleteRenderbuffer(Handle);
  }
}