#include "WaylandEglInterface.h"

#include "FileLogger.h"

#include <wayland-egl.h>

void WaylandEglInterface::initialize(wl_display* display)
{
    mEglDisplay = eglGetDisplay((EGLNativeDisplayType) display);
    if (mEglDisplay == EGL_NO_DISPLAY)
    {
        MLOG_ERROR("Can't create egl display")
        return;
    }

    EGLint major{0};
    EGLint minor{0};
    if (eglInitialize(mEglDisplay, &major, &minor) != EGL_TRUE)
    {
        MLOG_ERROR("Can't initialise egl display")
        return;
    }

    EGLint count{0};
    eglGetConfigs(mEglDisplay, nullptr, 0, &count);

    EGLConfig* configs;
    configs = static_cast<EGLConfig*>(calloc(count, sizeof* configs));

    EGLint n{0};
    EGLint config_attribs[] = {
            EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
            EGL_RED_SIZE, 8,
            EGL_GREEN_SIZE, 8,
            EGL_BLUE_SIZE, 8,
            EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
            EGL_NONE
    };
    eglChooseConfig(mEglDisplay, config_attribs, configs, count, &n);
    EGLint size{0};
    for (int i = 0; i < n; i++)
    {
        eglGetConfigAttrib(mEglDisplay, configs[i], EGL_BUFFER_SIZE, &size);
        // printf("Buffer size for config %d is %d\n", i, size);
        eglGetConfigAttrib(mEglDisplay, configs[i], EGL_RED_SIZE, &size);
        // printf("Red size for config %d is %d\n", i, size);

        // just choose the first one
        mEglConfig = configs[i];
        break;
    }

    static const EGLint context_attribs[] = {
            EGL_CONTEXT_CLIENT_VERSION, 2,
            EGL_NONE
    };
    mEglContext = eglCreateContext(mEglDisplay, mEglConfig, EGL_NO_CONTEXT, context_attribs);
}

EGLDisplay WaylandEglInterface::getDisplay() const
{
    return mEglDisplay;
}

EGLConfig WaylandEglInterface::getConfig() const
{
    return mEglConfig;
}

EGLContext WaylandEglInterface::getContext() const
{
    return mEglContext;
}
