#include <stdio.h>
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Check_Button.H>
#include <FL/Fl_Tooltip.H>
#include <FL/Fl_File_Chooser.H>
#include <FL/Fl_Color_Chooser.H>
#include <FL/Fl_Image.H>
#include <FL/Fl_Bitmap.H>
#include <FL/Fl_PNG_Image.H>
#include <FL/fl_ask.H>

enum {
    spacing = 20,
    gap = 10,
    button_w = 190,
    button_h = 38,
    option_h = 28,
    preview_h = 150,
    status_h = 70,
    win_w = 3 * button_w + 2 * gap + 2 * spacing,

    options_y = 60,
    buttons_y = options_y + option_h + gap,
    caption_y = buttons_y + 3 * button_h + 2 * gap + spacing,
    preview_y = caption_y + option_h,
    active_y = preview_y + preview_h + gap,
    status_y = active_y + option_h + spacing,
    win_h = status_y + status_h + spacing
};

static const unsigned char check_bits[] = {
    0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x30,
    0x00, 0x18, 0x00, 0x0c, 0x06, 0x06, 0x0c, 0x03,
    0x98, 0x01, 0xf0, 0x00, 0x60, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};

static const unsigned char cross_bits[] = {
    0x00, 0x00, 0x00, 0x00, 0x0c, 0x30, 0x18, 0x18,
    0x30, 0x0c, 0x60, 0x06, 0xc0, 0x03, 0x80, 0x01,
    0x80, 0x01, 0xc0, 0x03, 0x60, 0x06, 0x30, 0x0c,
    0x18, 0x18, 0x0c, 0x30, 0x00, 0x00, 0x00, 0x00
};

struct App {
    Fl_Box *status;
    Fl_Box *preview;
};

static void set_status(App *a, const char *text)
{
    a->status->copy_label(text);
    puts(text);
    fflush(stdout);
}

static void tooltip_cb(Fl_Widget *w, void *data)
{
    Fl_Check_Button *button = static_cast<Fl_Check_Button*>(w);
    App *a = static_cast<App*>(data);

    Fl_Tooltip::enable(button->value());
    set_status(a, button->value() ? "Tooltips enabled" : "Tooltips disabled");
}

static void labels_cb(Fl_Widget *w, void *data)
{
    Fl_Check_Button *button = static_cast<Fl_Check_Button*>(w);
    App *a = static_cast<App*>(data);
    int custom = button->value();

    fl_yes = custom ? "Yes, please" : "Yes";
    fl_no = custom ? "No, thanks" : "No";
    fl_ok = custom ? "Accept" : "OK";
    fl_cancel = custom ? "Dismiss" : "Cancel";
    fl_close = custom ? "Done" : "Close";
    fl_file_chooser_ok_label(fl_ok);

    set_status(a, custom ? "Custom dialog buttons" : "Default dialog buttons");
}

static void hotspot_cb(Fl_Widget *w, void *)
{
    Fl_Check_Button *button = static_cast<Fl_Check_Button*>(w);
    fl_message_hotspot(button->value());
}

static void message_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);

    fl_message_title("Information");
    fl_message_icon()->label("i");
    // The call returns only after the modal dialog has been closed.
    fl_message("This example has %d dialog buttons.", 9);
    fl_message_icon()->label(0);
    set_status(a, "Message closed");
}

static void alert_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);

    fl_message_title("Warning");
    fl_alert("Example warning: value %d is too large.", 100);
    set_status(a, "Alert closed");
}

static void ask_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);

    // fl_ask is deprecated, but is included to illustrate the textbook API.
    int answer = fl_ask("Do you like %s?", "FLTK");
    char text[80];
    snprintf(text, sizeof(text), "fl_ask returned %d (%s)",
             answer, answer ? "Yes" : "No");
    set_status(a, text);
}

static void choice_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    const char *choices[] = { "Cancel", "Read", "Write" };

    int answer = fl_choice("Choose an action for %d files.",
                           choices[0], choices[1], choices[2], 3);
    char text[80];
    snprintf(text, sizeof(text), "fl_choice returned %d (%s)",
             answer, choices[answer]);
    set_status(a, text);
}

static void input_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    const char *value = fl_input("Enter a name for %s:", "Student", "the demo");

    if (!value) {
        set_status(a, "Text input cancelled");
        return;
    }

    char text[256];
    snprintf(text, sizeof(text), "Name: %s", value);
    set_status(a, text);
}

static void password_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    const char *value = fl_password("Enter a demo password:", "");

    set_status(a, value ? "Password accepted" : "Password input cancelled");
}

static void file_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    const char *path = fl_file_chooser("Choose a PNG image", "*.png", ".");

    if (!path) {
        set_status(a, "File selection cancelled");
        return;
    }

    Fl_PNG_Image png(path);
    if (png.fail()) {
        fl_alert("Cannot load PNG image:\n%s", path);
        set_status(a, "PNG loading failed");
        return;
    }

    int max_w = a->preview->w() - 2 * spacing;
    int max_h = a->preview->h() - 2 * spacing;
    double scale = static_cast<double>(max_w) / png.w();
    double height_scale = static_cast<double>(max_h) / png.h();
    if (height_scale < scale)
        scale = height_scale;
    if (scale > 1.0)
        scale = 1.0;

    int width = static_cast<int>(png.w() * scale);
    int height = static_cast<int>(png.h() * scale);
    Fl_Image *picture = png.copy(width > 0 ? width : 1,
                                 height > 0 ? height : 1);
    delete a->preview->image();
    a->preview->image(picture);
    a->preview->redraw();

    // Chooser strings belong to FLTK; copy them before another chooser call.
    set_status(a, path);
}

static void directory_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    const char *path = fl_dir_chooser("Choose a directory", ".", 0);
    set_status(a, path ? path : "Directory selection cancelled");
}

static void color_cb(Fl_Widget *, void *data)
{
    App *a = static_cast<App*>(data);
    unsigned char r, g, b;
    Fl::get_color(a->preview->color(), r, g, b);

    if (!fl_color_chooser("Choose the preview background", r, g, b)) {
        set_status(a, "Color selection cancelled");
        return;
    }

    a->preview->color(fl_rgb_color(r, g, b));
    a->preview->redraw();

    char text[80];
    snprintf(text, sizeof(text), "Color: RGB(%d, %d, %d)", r, g, b);
    set_status(a, text);
}

static void active_cb(Fl_Widget *w, void *data)
{
    Fl_Check_Button *button = static_cast<Fl_Check_Button*>(w);
    App *a = static_cast<App*>(data);

    if (button->value())
        a->preview->activate();
    else
        a->preview->deactivate();

    a->preview->redraw();
    set_status(a, button->value() ? "Active preview: image()" :
                                   "Inactive preview: deimage()");
}

int main()
{
    App a = {};
    Fl_Bitmap check(check_bits, 16, 16);
    Fl_Bitmap cross(cross_bits, 16, 16);
    a.picture = check.copy(80, 80);
    Fl_Image *inactive_picture = cross.copy(80, 80);

    Fl_Tooltip::enable();
    Fl_Tooltip::delay(0.5);
    Fl_Tooltip::hoverdelay(0.1);
    Fl_Tooltip::size(14);
    Fl_Tooltip::color(fl_rgb_color(255, 255, 210));
    Fl_Tooltip::textcolor(FL_BLACK);
    fl_message_title_default("FLTK dialog example");
    fl_message_hotspot(0);

    Fl_Window win(win_w, win_h, "Tooltips, dialogs and images");

    Fl_Box title(spacing, spacing, win_w - 2 * spacing, option_h,
                 "Hover over a button, then click it");
    title.labelsize(18);

    Fl_Check_Button tooltips(spacing, options_y, button_w, option_h, "Tooltips");
    tooltips.value(1);
    tooltips.tooltip("Enable or disable tooltips on all widgets.");
    tooltips.callback(tooltip_cb, &a);

    Fl_Check_Button labels(spacing + button_w + gap, options_y,
                           button_w, option_h, "Custom button labels");
    labels.tooltip("Change fl_yes, fl_no, fl_ok, fl_cancel and fl_close.");
    labels.callback(labels_cb, &a);

    Fl_Check_Button hotspot(spacing + 2 * (button_w + gap), options_y,
                            button_w, option_h, "Dialog at pointer");
    hotspot.tooltip("Place common dialogs at the mouse pointer.");
    hotspot.callback(hotspot_cb);

    const char *names[] = {
        "fl_message", "fl_alert", "fl_ask",
        "fl_choice", "fl_input", "fl_password",
        "fl_file_chooser", "fl_dir_chooser", "fl_color_chooser"
    };
    Fl_Callback *callbacks[] = {
        message_cb, alert_cb, ask_cb,
        choice_cb, input_cb, password_cb,
        file_cb, directory_cb, color_cb
    };

    for (int i = 0; i < 9; ++i) {
        Fl_Button *button = new Fl_Button(spacing + (i % 3) * (button_w + gap),
                                          buttons_y + (i / 3) * (button_h + gap),
                                          button_w, button_h, names[i]);
        button->callback(callbacks[i], &a);

        char tip[160];
        snprintf(tip, sizeof(tip), "Button %d: open a modal %s dialog.",
                 i + 1, names[i]);
        // Unlike tooltip(), copy_tooltip() copies this temporary text.
        button->copy_tooltip(tip);
    }

    Fl_Box caption(spacing, caption_y, win_w - 2 * spacing, option_h,
                   "Fl_Bitmap preview; choose a PNG to replace it");

    Fl_Box preview(spacing, preview_y, win_w - 2 * spacing, preview_h);
    a.preview = &preview;
    preview.box(FL_DOWN_BOX);
    preview.color(FL_WHITE);
    preview.labelcolor(FL_DARK_GREEN);
    preview.image(check.copy(80, 80));
    preview.deimage(inactive_picture);
    preview.tooltip("image() is shown when active; deimage() when inactive.");

    Fl_Check_Button active(spacing, active_y, 260, option_h, "Preview active");
    active.value(1);
    active.tooltip("Uncheck to display the cross assigned with deimage().");
    active.callback(active_cb, &a);

    Fl_Box status(spacing, status_y, win_w - 2 * spacing, status_h, "Ready");
    a.status = &status;
    status.box(FL_DOWN_BOX);
    status.align(FL_ALIGN_LEFT | FL_ALIGN_INSIDE | FL_ALIGN_WRAP);

    win.end();
    win.show();

    int result = Fl::run();
    // Widgets borrow image pointers; the application owns the images.
    preview.image(0);
    preview.deimage(0);
    delete a.preview.image();
    delete inactive_picture;
    return result;
}
