#include "external_texture.h"
#include <android/hardware_buffer.h>
#include <glad/egl.h>
#include "logger.h"

bool ExternalTexture::create(AHardwareBuffer *hardwareBuffer)
{
    AHardwareBuffer_Desc desc{};
    AHardwareBuffer_describe(hardwareBuffer, &desc);
    EGLClientBuffer clientBuffer = eglGetNativeClientBufferANDROID(hardwareBuffer);
    EGLImageKHR eglImage = eglCreateImageKHR(eglGetCurrentDisplay(), EGL_NO_CONTEXT,
        EGL_NATIVE_BUFFER_ANDROID, clientBuffer, nullptr);
    if (eglImage == EGL_NO_IMAGE_KHR)
    {
        Logger::Log("Failed to create EGL image");
        return false;
    }
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_EXTERNAL_OES, texture);
    glEGLImageTargetTexture2DOES(GL_TEXTURE_EXTERNAL_OES, eglImage);
    eglDestroyImageKHR(eglGetCurrentDisplay(), eglImage);
    glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    return true;
}

void ExternalTexture::destroy()
{
    if (texture)
        glDeleteTextures(1, &texture);
    texture = 0;
}

void ExternalTexture::bind() const
{
    glBindTexture(GL_TEXTURE_EXTERNAL_OES, texture);
}

void ExternalTexture::unbind() const
{
    glBindTexture(GL_TEXTURE_EXTERNAL_OES, 0);
}

GLuint ExternalTexture::texture_id() const
{
    return texture;
}
