#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Output.H>
#include <FL/Fl_Button.H>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

struct State {
    Fl_Box *counter;
    Fl_Output *input;
    unsigned int ticks;
    bool running;
    bool input_open;
};

void on_timeout(void *data)
{
    State *state = static_cast<State*>(data);
    char text[64];
    snprintf(text, sizeof(text), "Timer ticks: %u", ++state->ticks);
    state->counter->copy_label(text);

    // A timeout fires once. Schedule the next tick from this callback.
    Fl::repeat_timeout(1.0, on_timeout, state);
}

void on_input(int fd, void *data)
{
    State *state = static_cast<State*>(data);
    char text[256];

    // Read only available bytes; getline() could wait for a whole line.
    int count = read(fd, text, sizeof(text) - 1);
    if (count > 0) {
        while (count > 0 && (text[count - 1] == '\n' || text[count - 1] == '\r'))
            --count;
        text[count] = '\0';
        state->input->value(text);
    } else if (count == 0 ||
               (errno != EINTR && errno != EAGAIN && errno != EWOULDBLOCK)) {
        // EOF stays readable: remove the handler to avoid a busy loop.
        state->input->value(count == 0 ? "End of input" : strerror(errno));
        Fl::remove_fd(fd);
        state->input_open = false;
    }
}

void on_pause(Fl_Widget *button, void *data)
{
    State *state = static_cast<State*>(data);
    if (state->running) {
        Fl::remove_fd(STDIN_FILENO);
        Fl::remove_timeout(on_timeout, state);
        button->label("Resume");
    } else {
        if (state->input_open)
            Fl::add_fd(STDIN_FILENO, FL_READ, on_input, state);
        Fl::add_timeout(1.0, on_timeout, state);
        button->label("Pause");
    }
    state->running = !state->running;
}

int main()
{
    Fl_Window window(480, 210, "FLTK: file descriptor and timer");
    Fl_Box instructions(20, 15, 440, 30,
                        "Type in the launching terminal, then press Enter.");
    instructions.labelsize(14);
    Fl_Box counter(20, 60, 440, 30, "Timer ticks: 0");
    counter.labelsize(18);
    Fl_Output input(80, 105, 380, 30, "Input:");
    Fl_Button pause(180, 160, 120, 30, "Pause");
    window.end();

    State state = { &counter, &input, 0, true, true };
    pause.callback(on_pause, &state);

    // FLTK watches stdin and calls on_input when it is readable.
    Fl::add_fd(STDIN_FILENO, FL_READ, on_input, &state);
    // Start the first tick; on_timeout schedules subsequent ticks.
    Fl::add_timeout(1.0, on_timeout, &state);

    window.show();
    int result = Fl::run(); // FLTK owns the main loop; no polling or threads.

    Fl::remove_fd(STDIN_FILENO);
    Fl::remove_timeout(on_timeout, &state);
    return result;
}
