package com.xyzshell.andinfo.libs.gpu.utils

import android.opengl.EGL14
import android.opengl.GLES10
import android.opengl.GLES20
import android.opengl.GLES30
import android.opengl.GLES31
import android.opengl.GLES32
import android.os.Build
import com.xyzshell.andinfo.libs.gpu.models.EglInformation
import com.xyzshell.andinfo.libs.gpu.models.GlInformation
import java.lang.reflect.Field

object EglUtils {
    fun getEglInformation(): EglInformation? {
        val eglDisplay = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY)

        if (eglDisplay == EGL14.EGL_NO_DISPLAY) {
            return null
        }

        val version = IntArray(2)
        if (!EGL14.eglInitialize(eglDisplay, version, 0, version, 1)) {
            return null
        }

        val eglVendor = EGL14.eglQueryString(eglDisplay, EGL14.EGL_VENDOR)
        val eglVersion = EGL14.eglQueryString(eglDisplay, EGL14.EGL_VERSION)
        val eglExtensions = EGL14.eglQueryString(eglDisplay, EGL14.EGL_EXTENSIONS)
            ?.split(" ")
            ?.filter { it.isNotBlank() }
        val eglClientApi = EGL14.eglQueryString(eglDisplay, EGL14.EGL_CLIENT_APIS)
            ?.split(" ")
            ?.filter { it.isNotBlank() }

        val glInformation = getGlInformation()

        EGL14.eglTerminate(eglDisplay)

        return EglInformation(
            eglVendor,
            eglVersion,
            eglExtensions,
            eglClientApi,
            glInformation,
        )
    }

    private fun getGlInformation(): GlInformation? {
        val glVendor = GLES10.glGetString(GLES10.GL_VENDOR)
        val glRenderer = GLES10.glGetString(GLES10.GL_RENDERER)
        val glVersion = GLES10.glGetString(GLES10.GL_VERSION)
        val glExtensions = GLES10.glGetString(GLES10.GL_EXTENSIONS)

        return GlInformation(
            glVendor,
            glRenderer,
            glVersion,
            glExtensions,
        )
    }
}
