#include <stdio.h>
#include <stdbool.h>

#ifndef _WIN32

#include <X11/keysym.h>

#define Window X11Window
#include <X11/Xlib.h>
#undef Window

#include "src/openwindow.h"

void xevent(Window * w, XEvent xev) {
    switch (xev.type)
    {
        case MotionNotify:
            printf("motion: %d %d\n", xev.xbutton.x, xev.xbutton.y);
            break;
        case KeyRelease:
            printf("release (%s)\n", XKeysymToString(XLookupKeysym(&xev.xkey, 0)));
            break;
        case KeyPress:
            if (XLookupKeysym(&xev.xkey, 0) == XK_Escape) w->close = true;
            printf("keypress (%s)\n", XKeysymToString(XLookupKeysym(&xev.xkey, 0)));
            break;
        case ButtonPress:
            printf("BPress: state = %d, button = %d, x = %d, y = %d\n", xev.xbutton.state, xev.xbutton.button, xev.xbutton.x, xev.xbutton.y);
            printf("Type=%d\n", (int)xev.xbutton.type);
            break;
        case ButtonRelease:
            printf("BRelease: state = %d, button = %d, x = %d, y = %d\n", xev.xbutton.state, xev.xbutton.button, xev.xbutton.x, xev.xbutton.y);
            printf("Type=%d\n", (int)xev.xbutton.type);
            break;
        default:
            printf("Unknown event!\n");
    }
}

#endif // _WIN32

const char * fss =
"#version 330 core\n"
"precision mediump float;"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
"    FragColor = vec4(0.0f, 1.0f, 0.0f, 1.0f);\n"
"}";

int main(void)
{
    Window w = openWindow("Window", 800, 600);

    windowSetEventHandler(&w, xevent);

    while (!w.close) {
        windowHandleEvents(&w);

        glClearColor(1, 1, 1, 1);
        glClear(GL_COLOR_BUFFER_BIT);
        glBegin(GL_TRIANGLES);
            glColor3f(1.0f, 0.0f, 0.0f);
            glVertex2f(-0.5, -0.5);
            glColor3f(0.0f, 1.0f, 0.0f);
            glVertex2f(0.5, -0.5);
            glColor3f(0.0f, 0.0f, 1.0f);
            glVertex2f(0.0, 0.5);
        glEnd();
        glFlush();

        windowDraw(w);
    }

    closeWindow(w);

    return 0;
}
