#ifndef STUDIO_DRAWING_H
#define STUDIO_DRAWING_H

#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <dlfcn.h>
#include <cairo/cairo.h>
#include <cairo/cairo-xlib.h>
#include <FL/x.H>
#include <FL/fl_draw.H>

struct _PangoLayout;
struct _PangoFontDescription;

// The existing Makefile links FLTK. Load the desktop's Cairo/Pango libraries
// at runtime, and retain native drawing if they are unavailable.
namespace drawing {
typedef ::_PangoLayout PangoLayout;
typedef ::_PangoFontDescription PangoFontDescription;

#define LOAD_CAIRO(name) bind(cairo_library_, name, "cairo_" #name)

class Api {
    template <class T> bool bind(void *library, T &function, const char *name)
    {
        void *symbol = dlsym(library, name);
        if (!symbol || sizeof(function) != sizeof(symbol))
            return false;
        std::memcpy(&function, &symbol, sizeof(function));
        return true;
    }
    void *cairo_library_, *pango_library_;

public:
    bool ready;
    cairo_surface_t *(*xlib_surface_create)(Display *, Drawable, Visual *, int,
                                            int);
    void (*surface_destroy)(cairo_surface_t *);
    void (*surface_flush)(cairo_surface_t *);
    void (*surface_mark_dirty)(cairo_surface_t *);
    cairo_status_t (*surface_status)(cairo_surface_t *);
    cairo_t *(*create)(cairo_surface_t *);
    void (*destroy)(cairo_t *);
    void (*save)(cairo_t *);
    void (*restore)(cairo_t *);
    void (*rectangle)(cairo_t *, double, double, double, double);
    void (*clip)(cairo_t *);
    void (*new_path)(cairo_t *);
    void (*move_to)(cairo_t *, double, double);
    void (*line_to)(cairo_t *, double, double);
    void (*curve_to)(cairo_t *, double, double, double, double, double, double);
    void (*close_path)(cairo_t *);
    void (*arc)(cairo_t *, double, double, double, double, double);
    void (*translate)(cairo_t *, double, double);
    void (*scale)(cairo_t *, double, double);
    void (*set_source_rgb)(cairo_t *, double, double, double);
    void (*set_line_width)(cairo_t *, double);
    void (*set_line_cap)(cairo_t *, cairo_line_cap_t);
    void (*set_line_join)(cairo_t *, cairo_line_join_t);
    void (*set_dash)(cairo_t *, const double *, int, double);
    void (*fill)(cairo_t *);
    void (*stroke)(cairo_t *);
    void (*set_antialias)(cairo_t *, cairo_antialias_t);
    void (*set_fill_rule)(cairo_t *, cairo_fill_rule_t);
    cairo_font_options_t *(*font_options_create)();
    void (*font_options_destroy)(cairo_font_options_t *);
    void (*font_options_set_antialias)(cairo_font_options_t *,
                                       cairo_antialias_t);
    void (*font_options_set_hint_style)(cairo_font_options_t *,
                                        cairo_hint_style_t);
    void (*font_options_set_hint_metrics)(cairo_font_options_t *,
                                          cairo_hint_metrics_t);
    void (*set_font_options)(cairo_t *, const cairo_font_options_t *);
    PangoLayout *(*create_layout)(cairo_t *);
    void (*layout_set_text)(PangoLayout *, const char *, int);
    void (*layout_set_font_description)(PangoLayout *,
                                        const PangoFontDescription *);
    void (*layout_get_size)(PangoLayout *, int *, int *);
    int (*layout_get_baseline)(PangoLayout *);
    PangoFontDescription *(*font_description_new)();
    void (*font_description_free)(PangoFontDescription *);
    void (*font_description_set_family)(PangoFontDescription *, const char *);
    void (*font_description_set_weight)(PangoFontDescription *, int);
    void (*font_description_set_absolute_size)(PangoFontDescription *, double);
    void (*show_layout)(cairo_t *, PangoLayout *);
    void (*object_unref)(void *);

private:
    bool load_surface_functions()
    {
        return LOAD_CAIRO(xlib_surface_create) && LOAD_CAIRO(surface_destroy)
               && LOAD_CAIRO(surface_flush) && LOAD_CAIRO(surface_mark_dirty)
               && LOAD_CAIRO(surface_status);
    }

    bool load_path_functions()
    {
        return LOAD_CAIRO(create) && LOAD_CAIRO(destroy) && LOAD_CAIRO(save)
               && LOAD_CAIRO(restore) && LOAD_CAIRO(rectangle)
               && LOAD_CAIRO(clip) && LOAD_CAIRO(new_path)
               && LOAD_CAIRO(move_to) && LOAD_CAIRO(line_to)
               && LOAD_CAIRO(curve_to) && LOAD_CAIRO(close_path);
    }

    bool load_paint_functions()
    {
        return LOAD_CAIRO(arc) && LOAD_CAIRO(translate) && LOAD_CAIRO(scale)
               && LOAD_CAIRO(set_source_rgb) && LOAD_CAIRO(set_line_width)
               && LOAD_CAIRO(set_line_cap) && LOAD_CAIRO(set_line_join)
               && LOAD_CAIRO(set_dash) && LOAD_CAIRO(fill) && LOAD_CAIRO(stroke)
               && LOAD_CAIRO(set_antialias) && LOAD_CAIRO(set_fill_rule);
    }

    bool load_font_options()
    {
        return LOAD_CAIRO(font_options_create)
               && LOAD_CAIRO(font_options_destroy)
               && LOAD_CAIRO(font_options_set_antialias)
               && LOAD_CAIRO(font_options_set_hint_style)
               && LOAD_CAIRO(font_options_set_hint_metrics)
               && LOAD_CAIRO(set_font_options);
    }

    bool load_layout_functions()
    {
        return bind(pango_library_, create_layout, "pango_cairo_create_layout")
               && bind(pango_library_, layout_set_text, "pango_layout_set_text")
               && bind(pango_library_, layout_set_font_description,
                       "pango_layout_set_font_description")
               && bind(pango_library_, layout_get_size, "pango_layout_get_size")
               && bind(pango_library_, layout_get_baseline,
                       "pango_layout_get_baseline");
    }

    bool load_font_functions()
    {
        return bind(pango_library_, font_description_new,
                    "pango_font_description_new")
               && bind(pango_library_, font_description_free,
                       "pango_font_description_free")
               && bind(pango_library_, font_description_set_family,
                       "pango_font_description_set_family")
               && bind(pango_library_, font_description_set_weight,
                       "pango_font_description_set_weight")
               && bind(pango_library_, font_description_set_absolute_size,
                       "pango_font_description_set_absolute_size")
               && bind(pango_library_, show_layout, "pango_cairo_show_layout")
               && bind(pango_library_, object_unref, "g_object_unref");
    }

public:
    Api() : cairo_library_(0), pango_library_(0), ready(false)
    {
        if (std::getenv("FOURIER_STUDIO_NATIVE_RENDER"))
            return;
        cairo_library_ = dlopen("libcairo.so.2", RTLD_NOW | RTLD_LOCAL);
        pango_library_ =
            dlopen("libpangocairo-1.0.so.0", RTLD_NOW | RTLD_LOCAL);
        if (!cairo_library_ || !pango_library_)
            return;
        ready = load_surface_functions() && load_path_functions()
                && load_paint_functions() && load_font_options()
                && load_layout_functions() && load_font_functions();
    }
    ~Api()
    {
        if (pango_library_)
            dlclose(pango_library_);
        if (cairo_library_)
            dlclose(cairo_library_);
    }
};

#undef LOAD_CAIRO

inline Api &api()
{
    static Api instance;
    return instance;
}
class Scope;
static Scope *current = 0;

class Scope {
    Scope *previous_;
    Scope(const Scope &);
    Scope &operator=(const Scope &);

public:
    cairo_surface_t *surface;
    cairo_t *context;
    PangoLayout *layout;
    PangoFontDescription *font;
    double width;
    bool first_vertex;

private:
    bool initialize_surface(Fl_Widget *widget)
    {
        if (!api().ready || !fl_display || !fl_window || !widget->window())
            return false;
        surface = api().xlib_surface_create(
            fl_display, fl_window, fl_visual->visual, widget->window()->w(),
            widget->window()->h());
        return api().surface_status(surface) == CAIRO_STATUS_SUCCESS;
    }

    void clip_widget(Fl_Widget *widget)
    {
        // Preserve FLTK's current damage/parent clip.
        int X, Y, W, H;
        ::fl_clip_box(widget->x(), widget->y(), widget->w(), widget->h(), X, Y,
                      W, H);
        api().rectangle(context, X, Y, W, H);
        api().clip(context);
    }

    void configure_font_options()
    {
        cairo_font_options_t *options = api().font_options_create();
        api().font_options_set_antialias(options, CAIRO_ANTIALIAS_GRAY);
        api().font_options_set_hint_style(options, CAIRO_HINT_STYLE_SLIGHT);
        api().font_options_set_hint_metrics(options, CAIRO_HINT_METRICS_OFF);
        api().set_font_options(context, options);
        api().font_options_destroy(options);
    }

    void initialize_context(Fl_Widget *widget)
    {
        context = api().create(surface);
        api().set_antialias(context, CAIRO_ANTIALIAS_BEST);
        api().set_line_width(context, 1.0);
        api().set_line_cap(context, CAIRO_LINE_CAP_ROUND);
        api().set_line_join(context, CAIRO_LINE_JOIN_ROUND);
        clip_widget(widget);
        configure_font_options();
    }

    void initialize_layout()
    {
        layout = api().create_layout(context);
        font = api().font_description_new();
        api().font_description_set_family(font, "Inter");
        api().font_description_set_weight(font, 400);
        api().font_description_set_absolute_size(font, 13.0 * 1024);
        api().layout_set_font_description(layout, font);
    }

public:
    Scope(Fl_Widget *widget)
        : previous_(current), surface(0), context(0), layout(0), font(0),
          width(1.0), first_vertex(true)
    {
        if (previous_ && previous_->surface)
            api().surface_flush(previous_->surface);
        current = this;
        if (!initialize_surface(widget))
            return;
        initialize_context(widget);
        initialize_layout();
    }
    ~Scope()
    {
        if (layout)
            api().object_unref(layout);
        if (font)
            api().font_description_free(font);
        if (surface)
            api().surface_flush(surface);
        if (context)
            api().destroy(context);
        if (surface)
            api().surface_destroy(surface);
        current = previous_;
        // Native children (e.g. table scrollbars) may have drawn to the same
        // drawable.
        if (current && current->surface)
            api().surface_mark_dirty(current->surface);
    }
};

inline bool active() { return current && current->context; }
inline cairo_t *context() { return current->context; }
inline void flush()
{
    if (active())
        api().surface_flush(current->surface);
}

inline void color(Fl_Color c)
{
    ::fl_color(c);
    if (!active())
        return;
    unsigned char r, g, b;
    Fl::get_color(c, r, g, b);
    api().set_source_rgb(context(), r / 255.0, g / 255.0, b / 255.0);
}

inline void font(Fl_Font f, int size)
{
    ::fl_font(f, size);
    if (!active())
        return;
    api().font_description_set_weight(current->font,
                                      f == FL_HELVETICA_BOLD ? 600 : 400);
    api().font_description_set_absolute_size(current->font, size * 1024.0);
    api().layout_set_font_description(current->layout, current->font);
}

inline void draw(const char *text, double x, double baseline)
{
    if (!active()) {
        ::fl_draw(text, static_cast<int>(x), static_cast<int>(baseline));
        return;
    }
    api().layout_set_text(current->layout, text, -1);
    double ascent = api().layout_get_baseline(current->layout) / 1024.0;
    api().move_to(context(), x, baseline - ascent);
    api().show_layout(context(), current->layout);
}

inline void draw(const char *text, int x, int y, int w, int h, Fl_Align align)
{
    if (!active()) {
        ::fl_draw(text, x, y, w, h, align);
        return;
    }
    api().layout_set_text(current->layout, text, -1);
    int width, height;
    api().layout_get_size(current->layout, &width, &height);
    double W = width / 1024.0, H = height / 1024.0;
    double X = align & FL_ALIGN_LEFT
                   ? x
                   : (align & FL_ALIGN_RIGHT ? x + w - W : x + (w - W) / 2.0);
    double Y = align & FL_ALIGN_TOP
                   ? y
                   : (align & FL_ALIGN_BOTTOM ? y + h - H : y + (h - H) / 2.0);
    api().move_to(context(), X, Y);
    api().show_layout(context(), current->layout);
}

inline void rectf(int x, int y, int w, int h)
{
    if (!active()) {
        ::fl_rectf(x, y, w, h);
        return;
    }
    api().rectangle(context(), x, y, w, h);
    api().fill(context());
}

inline void native_round_rect(int x, int y, int w, int h, int r)
{
    ::fl_rectf(x + r, y, w - 2 * r, h);
    ::fl_rectf(x, y + r, w, h - 2 * r);
    ::fl_pie(x, y, 2 * r, 2 * r, 0, 360);
    ::fl_pie(x + w - 2 * r, y, 2 * r, 2 * r, 0, 360);
    ::fl_pie(x, y + h - 2 * r, 2 * r, 2 * r, 0, 360);
    ::fl_pie(x + w - 2 * r, y + h - 2 * r, 2 * r, 2 * r, 0, 360);
}

inline void rounded_path(int x, int y, int w, int h, int r)
{
    double k = r * 0.5522847498307936;
    api().new_path(context());
    api().move_to(context(), x + r, y);
    api().line_to(context(), x + w - r, y);
    api().curve_to(context(), x + w - r + k, y, x + w, y + r - k, x + w, y + r);
    api().line_to(context(), x + w, y + h - r);
    api().curve_to(context(), x + w, y + h - r + k, x + w - r + k, y + h,
                   x + w - r, y + h);
    api().line_to(context(), x + r, y + h);
    api().curve_to(context(), x + r - k, y + h, x, y + h - r + k, x, y + h - r);
    api().line_to(context(), x, y + r);
    api().curve_to(context(), x, y + r - k, x + r - k, y, x + r, y);
    api().close_path(context());
}

inline void round_rect(int x, int y, int w, int h, int r, Fl_Color c)
{
    color(c);
    if (w <= 0 || h <= 0)
        return;
    r = std::min(r, std::min(w, h) / 2);
    if (!active()) {
        native_round_rect(x, y, w, h, r);
        return;
    }
    rounded_path(x, y, w, h, r);
    api().fill(context());
}

inline void pie(int x, int y, int w, int h, double start, double end)
{
    if (!active()) {
        ::fl_pie(x, y, w, h, start, end);
        return;
    }
    api().new_path(context());
    api().save(context());
    api().translate(context(), x + w / 2.0, y + h / 2.0);
    api().scale(context(), w / 2.0, h / 2.0);
    api().arc(context(), 0, 0, 1, start * 0.0174532925199433,
              end * 0.0174532925199433);
    api().restore(context());
    api().fill(context());
}

inline void line_style(int style, int width = 0)
{
    ::fl_line_style(style, width);
    if (!active())
        return;
    current->width = width ? width : 1;
    api().set_line_width(context(), current->width);
    double dashed[] = { 4, 3 }, dotted[] = { 1, 3 };
    if ((style & 255) == FL_DASH)
        api().set_dash(context(), dashed, 2, 0);
    else if ((style & 255) == FL_DOT)
        api().set_dash(context(), dotted, 2, 0);
    else
        api().set_dash(context(), 0, 0, 0);
}

inline void line(double x1, double y1, double x2, double y2)
{
    if (!active()) {
        ::fl_line(static_cast<int>(x1), static_cast<int>(y1),
                  static_cast<int>(x2), static_cast<int>(y2));
        return;
    }
    double snap = current->width == 1.0 ? 0.5 : 0.0;
    api().new_path(context());
    api().move_to(context(), x1 + snap, y1 + snap);
    api().line_to(context(), x2 + snap, y2 + snap);
    api().stroke(context());
}

inline void line(int x1, int y1, int x2, int y2, int x3, int y3)
{
    if (!active()) {
        ::fl_line(x1, y1, x2, y2, x3, y3);
        return;
    }
    double snap = current->width == 1.0 ? 0.5 : 0.0;
    api().new_path(context());
    api().move_to(context(), x1 + snap, y1 + snap);
    api().line_to(context(), x2 + snap, y2 + snap);
    api().line_to(context(), x3 + snap, y3 + snap);
    api().stroke(context());
}

inline void polygon(int x1, int y1, int x2, int y2, int x3, int y3)
{
    if (!active()) {
        ::fl_polygon(x1, y1, x2, y2, x3, y3);
        return;
    }
    api().new_path(context());
    api().move_to(context(), x1, y1);
    api().line_to(context(), x2, y2);
    api().line_to(context(), x3, y3);
    api().close_path(context());
    api().fill(context());
}

inline void push_clip(int x, int y, int w, int h)
{
    ::fl_push_clip(x, y, w, h);
    if (!active())
        return;
    api().save(context());
    api().rectangle(context(), x, y, w, h);
    api().clip(context());
}

inline void pop_clip()
{
    if (active())
        api().restore(context());
    ::fl_pop_clip();
}

inline void begin_line()
{
    if (!active()) {
        ::fl_begin_line();
        return;
    }
    api().new_path(context());
    current->first_vertex = true;
}

inline void vertex(double x, double y)
{
    if (!active()) {
        ::fl_vertex(x, y);
        return;
    }
    if (current->first_vertex)
        api().move_to(context(), x, y);
    else
        api().line_to(context(), x, y);
    current->first_vertex = false;
}

inline void end_line()
{
    if (!active()) {
        ::fl_end_line();
        return;
    }
    api().stroke(context());
}

inline void begin_complex_polygon()
{
    if (!active()) {
        ::fl_begin_complex_polygon();
        return;
    }
    begin_line();
}

inline void end_complex_polygon()
{
    if (!active()) {
        ::fl_end_complex_polygon();
        return;
    }
    api().close_path(context());
    api().set_fill_rule(context(), CAIRO_FILL_RULE_EVEN_ODD);
    api().fill(context());
    api().set_fill_rule(context(), CAIRO_FILL_RULE_WINDING);
}
} // namespace drawing
#endif
