#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/select.h>

#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/x.H>

struct App {
    Fl_Window *window;
    Fl_Box *message;
    Fl_Box *timer;
    int seconds;
    bool input_open;
};

static int connect_x11()
{
    Display *display = XOpenDisplay(0);
    if (!display)
        return -1;

    int fd = ConnectionNumber(display);
    fl_open_display(display);
    return fd;
}

static void timer_cb(void *data)
{
    App *a = static_cast<App*>(data);

    char text[64];
    sprintf(text, "Elapsed: %d seconds", ++a->seconds);
    a->timer->copy_label(text);

    Fl::repeat_timeout(1.0, timer_cb, data);
}

static void read_terminal(App *a)
{
    char text[256];
    int n = read(STDIN_FILENO, text, sizeof(text) - 1);

    if (n == 0) {
        a->input_open = false;
        a->message->copy_label("Input closed");
        return;
    }

    if (n < 0)
        return;

    text[n] = '\0';

    if (text[n - 1] == '\n')
        text[n - 1] = '\0';

    if (strcmp(text, "quit") == 0)
        a->window->hide();
    else
        a->message->copy_label(text);
}

static void event_loop(App *a, int xfd)
{
    Fl::add_timeout(1.0, timer_cb, a);

    while (a->window->shown()) {
        fd_set fds;
        FD_ZERO(&fds);
        FD_SET(xfd, &fds);

        if (a->input_open)
            FD_SET(STDIN_FILENO, &fds);

        timeval timeout = { 0, 50000 };
        int maxfd = xfd > STDIN_FILENO ? xfd : STDIN_FILENO;

        int result = select(maxfd + 1, &fds, 0, 0, &timeout);

        if (result < 0) {
            if (errno == EINTR)
                continue;
            perror("select");
            break;
        }

        if (result > 0 && a->input_open && FD_ISSET(STDIN_FILENO, &fds))
            read_terminal(a);

        Fl::wait(0.0);
    }

    Fl::remove_timeout(timer_cb, a);
}

int main()
{
    int xfd = connect_x11();
    if (xfd < 0) {
        fprintf(stderr, "Cannot connect to X11\n");
        return 1;
    }

    Fl_Window window(400, 180, "Terminal input");
    Fl_Box message(20, 20, 360, 60, "Type in the terminal");
    Fl_Box timer(20, 100, 360, 50, "Elapsed: 0 seconds");
    window.end();

    App app = { &window, &message, &timer, 0, true };

    window.show();
    event_loop(&app, xfd);

    return 0;
}
