#include "WaylandEglWindowInterface.h"

#include "FileLogger.h"
#include "OpenGlInterface.h"

#include <wayland-egl.h>

WaylandEglWindowInterface::WaylandEglWindowInterface(WaylandEglInterface* eglInterface)
    : mEglInterface(eglInterface)
{

}

void WaylandEglWindowInterface::initialize(wl_surface* surface, int width, int height)
{
    if (mEglSurface)
    {
        return;
    }

    mEglWindow = wl_egl_window_create(surface, width, height);
    if (mEglWindow == EGL_NO_SURFACE)
    {
        MLOG_ERROR("Can't create egl window");
        return;
    }

    mEglSurface = eglCreateWindowSurface(mEglInterface->getDisplay(), mEglInterface->getConfig(), reinterpret_cast<EGLNativeWindowType>(mEglWindow), nullptr);

    if (!mEglSurface)
    {
        switch(eglGetError())
        {
            case EGL_BAD_DISPLAY:
                fprintf(stderr, "EGL_BAD_DISPLAY\n");
                break;
            case EGL_NOT_INITIALIZED:
                fprintf(stderr, "EGL_NOT_INITIALIZED\n");
                break;
            case EGL_BAD_CONFIG:
                fprintf(stderr, "EGL_BAD_CONFIG\n");
                break;
            case EGL_BAD_NATIVE_WINDOW:
                fprintf(stderr, "EGL_BAD_NATIVE_WINDOW\n");
                break;
            case EGL_BAD_ATTRIBUTE:
                fprintf(stderr, "EGL_BAD_ATTRIBUTE\n");
                break;
            case EGL_BAD_ALLOC:
                fprintf(stderr, "EGL_BAD_ALLOC\n");
                break;
            case EGL_BAD_MATCH:
                fprintf(stderr, "EGL_BAD_MATCH\n");
                break;
            default:
                fprintf(stderr, "Unknown EGL error\n");
        }
        MLOG_ERROR("Created surface failed");
    }
}

void WaylandEglWindowInterface::draw()
{
    if (!mEglSurface)
    {
        return;
    }

    if (!eglMakeCurrent(mEglInterface->getDisplay(), mEglSurface, mEglSurface, mEglInterface->getContext()))
    {
        MLOG_ERROR("Made current failed");
    }

    OpenGlInterface::draw();

    if (!eglSwapBuffers(mEglInterface->getDisplay(), mEglSurface))
    {
        MLOG_ERROR("Swapped buffers failed");
    }
}
