#define _GNU_SOURCE
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <xkbcommon/xkbcommon.h>
#include "c8ui-private.h"

/* Small controls: check box, radio buttons, the progress ring, pictures */

#define BOX 20 // a check box's or radio button's mark
#define MARK_GAP 10 // between the mark and its label
#define ROW 32 // height of a check box or a radio item

static struct c8ui_font label_font(void) {
	return c8ui_text_font(C8UI_TEXT_BODY);
}

static double label_width(struct c8ui_widget *w, const char *text) {
	double tw, th;
	c8ui_text_size(c8ui_widget_font(w), label_font(), text, 0, 0, &tw, &th);
	return tw;
}

/* A label to the right of a mark, centred on a row at y */
static void draw_label(struct c8ui_widget *w, cairo_t *cr, const char *text,
		double x, double y, double width, double alpha) {
	struct c8ui_colors c = c8ui_widget_colors(w);
	double tw, th;
	c8ui_text_size(c8ui_widget_font(w), label_font(), text, 0, 0, &tw, &th);
	c8ui_set_source(cr, c.fg, alpha);
	c8ui_text_draw(cr, c8ui_widget_font(w), label_font(), text, x,
		y + (ROW - th) / 2, width, 1);
}

/* The square or circle of a mark: border, and a fill while pressed or
 * hovered */
static void mark_path(cairo_t *cr, double x, double y, bool round) {
	cairo_new_path(cr);
	if (round) {
		cairo_arc(cr, x + BOX / 2.0, y + BOX / 2.0, BOX / 2.0 - 1, 0, 2 * M_PI);
	} else {
		cairo_rectangle(cr, x + 1, y + 1, BOX - 2, BOX - 2);
	}
}

static void draw_mark(struct c8ui_widget *w, cairo_t *cr, double x, double y,
		bool round, bool hover, bool down) {
	struct c8ui_colors c = c8ui_widget_colors(w);
	mark_path(cr, x, y, round);
	if (down) {
		c8ui_set_source(cr, c.fg, c.fill * 2.5);
		cairo_fill_preserve(cr);
	} else if (hover) {
		c8ui_set_source(cr, c.fg, c.fill);
		cairo_fill_preserve(cr);
	}
	c8ui_set_source(cr, c.fg, w->disabled ? c.border : hover ? 1 :
		c.border_hover);
	cairo_set_line_width(cr, 2);
	cairo_stroke(cr);
}

/* Check box */

struct checkbox {
	char *label;
	bool checked;
	c8ui_action_fn fn;
	void *data;
};

static void checkbox_measure(struct c8ui_widget *w, double avail,
		double *width, double *height) {
	struct checkbox *cb = w->data;
	*width = BOX + MARK_GAP + label_width(w, cb->label);
	if (*width > avail) {
		*width = avail;
	}
	*height = ROW;
}

static void checkbox_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct checkbox *cb = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	double x = w->rect.x, y = w->rect.y + (ROW - BOX) / 2;
	draw_mark(w, cr, x, y, false, w->hovered, w->pressed && w->hovered);
	if (cb->checked) {
		c8ui_set_source(cr, c.fg, w->disabled ? 0.4 : 1);
		cairo_set_line_width(cr, 2.2);
		cairo_move_to(cr, x + 5, y + 10);
		cairo_line_to(cr, x + 8.5, y + 13.5);
		cairo_line_to(cr, x + 15, y + 6.5);
		cairo_stroke(cr);
	}
	draw_label(w, cr, cb->label, x + BOX + MARK_GAP, w->rect.y,
		w->rect.width - BOX - MARK_GAP, w->disabled ? 0.4 : 1);
}

static void checkbox_flip(struct c8ui_widget *w) {
	struct checkbox *cb = w->data;
	cb->checked = !cb->checked;
	c8ui_widget_queue_draw(w);
	if (cb->fn) {
		cb->fn(w, cb->data);
	}
}

static bool checkbox_event(struct c8ui_widget *w,
		const struct c8ui_event *ev) {
	/* Space ticks it; Enter is left for the form's default button */
	if (ev->type == C8UI_EVENT_KEY && ev->sym != XKB_KEY_space) {
		return false;
	}
	return c8ui_push_event(w, ev, checkbox_flip);
}

static void checkbox_destroy(struct c8ui_widget *w) {
	struct checkbox *cb = w->data;
	free(cb->label);
	free(cb);
}

static const struct c8ui_widget_impl checkbox_impl = {
	.name = "checkbox",
	.measure = checkbox_measure,
	.draw = checkbox_draw,
	.event = checkbox_event,
	.destroy = checkbox_destroy,
};

struct c8ui_widget *c8ui_checkbox_new(const char *label, bool checked,
		c8ui_action_fn fn, void *data) {
	struct checkbox *cb = calloc(1, sizeof(*cb));
	cb->label = strdup(label ? label : "");
	cb->checked = checked;
	cb->fn = fn;
	cb->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&checkbox_impl, cb);
	w->focusable = true;
	w->cursor = C8UI_CURSOR_POINTER;
	return w;
}

bool c8ui_checkbox_get(struct c8ui_widget *w) {
	return ((struct checkbox *)w->data)->checked;
}

void c8ui_checkbox_set(struct c8ui_widget *w, bool checked) {
	((struct checkbox *)w->data)->checked = checked;
	c8ui_widget_queue_draw(w);
}

/* Radio buttons */

struct radio {
	char *header;
	char **items;
	int count, selected, hover, pressed;
	c8ui_action_fn fn;
	void *data;
};

static double radio_header_height(struct c8ui_widget *w, double avail) {
	struct radio *r = w->data;
	return c8ui_header_height(w, r->header, avail, NULL);
}

static void radio_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct radio *r = w->data;
	double mw = 0;
	for (int i = 0; i < r->count; i++) {
		double iw = BOX + MARK_GAP + label_width(w, r->items[i]);
		mw = iw > mw ? iw : mw;
	}
	if (r->header) {
		double hw = label_width(w, r->header);
		mw = hw > mw ? hw : mw;
	}
	*width = mw < avail ? mw : avail;
	*height = radio_header_height(w, avail) + r->count * ROW;
}

static int radio_at(struct c8ui_widget *w, double x, double y) {
	struct radio *r = w->data;
	if (!c8ui_rect_contains(&w->rect, x, y)) {
		return -1;
	}
	double top = w->rect.y + radio_header_height(w, w->rect.width);
	int i = (int)floor((y - top) / ROW);
	return y >= top && i < r->count ? i : -1;
}

static void radio_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct radio *r = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	double y = w->rect.y;
	c8ui_header_draw(w, cr, r->header, 1);
	y += radio_header_height(w, w->rect.width);
	for (int i = 0; i < r->count; i++, y += ROW) {
		double my = y + (ROW - BOX) / 2;
		bool hover = i == r->hover;
		draw_mark(w, cr, w->rect.x, my, true, hover,
			hover && i == r->pressed && w->pressed);
		if (i == r->selected) {
			c8ui_set_source(cr, c.fg, w->disabled ? 0.4 : 1);
			cairo_new_path(cr);
			cairo_arc(cr, w->rect.x + BOX / 2.0, my + BOX / 2.0, 5, 0,
				2 * M_PI);
			cairo_fill(cr);
		}
		/* The keyboard is on the chosen one */
		if (i == r->selected && w->focused && w->root &&
				w->root->focus_visible) {
			c8ui_set_source(cr, c.fg, 1);
			double lw = label_width(w, r->items[i]);
			c8ui_dotted_rect(cr, w->rect.x + BOX + MARK_GAP - 3.5, y + 3.5,
				lw + 7, ROW - 7);
		}
		draw_label(w, cr, r->items[i], w->rect.x + BOX + MARK_GAP, y,
			w->rect.width - BOX - MARK_GAP, w->disabled ? 0.4 : 1);
	}
}

static void radio_select(struct c8ui_widget *w, int i) {
	struct radio *r = w->data;
	if (i < 0 || i >= r->count || i == r->selected) {
		return;
	}
	r->selected = i;
	c8ui_widget_queue_draw(w);
	if (r->fn) {
		r->fn(w, r->data);
	}
}

static bool radio_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct radio *r = w->data;
	switch (ev->type) {
	case C8UI_EVENT_MOTION:
		c8ui_hover_item(w, &r->hover, radio_at(w, ev->x, ev->y));
		return false;
	case C8UI_EVENT_LEAVE:
		c8ui_hover_item(w, &r->hover, -1);
		return false;
	case C8UI_EVENT_PRESS:
		if (ev->button != C8UI_BUTTON_LEFT) {
			return false;
		}
		r->pressed = radio_at(w, ev->x, ev->y);
		return true;
	case C8UI_EVENT_RELEASE:
		if (r->pressed >= 0 && radio_at(w, ev->x, ev->y) == r->pressed) {
			radio_select(w, r->pressed);
		}
		r->pressed = -1;
		c8ui_widget_queue_draw(w);
		return true;
	case C8UI_EVENT_KEY:
		if (ev->sym == XKB_KEY_Up || ev->sym == XKB_KEY_Left) {
			radio_select(w, r->selected - 1);
			return true;
		}
		if (ev->sym == XKB_KEY_Down || ev->sym == XKB_KEY_Right) {
			radio_select(w, r->selected + 1);
			return true;
		}
		return false;
	case C8UI_EVENT_FOCUS_IN:
	case C8UI_EVENT_FOCUS_OUT:
		c8ui_widget_queue_draw(w);
		return false;
	default:
		return false;
	}
}

static void radio_destroy(struct c8ui_widget *w) {
	struct radio *r = w->data;
	for (int i = 0; i < r->count; i++) {
		free(r->items[i]);
	}
	free(r->items);
	free(r->header);
	free(r);
}

static const struct c8ui_widget_impl radio_impl = {
	.name = "radio",
	.measure = radio_measure,
	.draw = radio_draw,
	.event = radio_event,
	.destroy = radio_destroy,
};

struct c8ui_widget *c8ui_radio_new(const char *header,
		const char *const *items, int count, int selected, c8ui_action_fn fn,
		void *data) {
	struct radio *r = calloc(1, sizeof(*r));
	r->header = c8ui_dup_or_null(header);
	r->items = calloc(count > 0 ? count : 1, sizeof(char *));
	for (int i = 0; i < count; i++) {
		r->items[i] = strdup(items[i] ? items[i] : "");
	}
	r->count = count;
	r->selected = selected;
	r->hover = r->pressed = -1;
	r->fn = fn;
	r->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&radio_impl, r);
	w->focusable = true;
	w->cursor = C8UI_CURSOR_POINTER;
	return w;
}

int c8ui_radio_get(struct c8ui_widget *w) {
	return ((struct radio *)w->data)->selected;
}

void c8ui_radio_set(struct c8ui_widget *w, int selected) {
	((struct radio *)w->data)->selected = selected;
	c8ui_widget_queue_draw(w);
}

/* Progress ring */

#define RING_DOTS 5
#define RING_MS 2600 // one round of the dots, pause included
#define RING_STAGGER 0.07 // how far each dot trails the one before

struct ring {
	double size;
	bool active;
	int64_t start;
};

static void ring_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct ring *r = w->data;
	*width = *height = r->size;
}

/* Where a dot is, in turns, t (0 to 1) into the round: quick through the
 * bottom, slow over the top, and gone for the pause at the end */
static bool ring_angle(double t, double *turns) {
	const double run = 0.85;
	if (t < 0 || t > run) {
		return false;
	}
	double u = t / run;
	/* Two turns, easing so it hurries and lingers */
	*turns = 2 * u - 0.12 * sin(4 * M_PI * u) / M_PI;
	return true;
}

static void ring_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct ring *r = w->data;
	if (!r->active) {
		return;
	}
	c8ui_widget_animate(w); // keeps it going, and starts it once shown
	int64_t now = w->root ? w->root->now : 0;
	if (r->start == 0) {
		r->start = now ? now : 1;
	}
	struct c8ui_colors c = c8ui_widget_colors(w);
	double t = (double)((now - r->start) % RING_MS) / RING_MS;
	double cx = w->rect.x + w->rect.width / 2;
	double cy = w->rect.y + w->rect.height / 2;
	double radius = r->size / 2 - r->size / 12;
	double dot = r->size / 12 < 1.5 ? 1.5 : r->size / 12;
	c8ui_set_source(cr, c.accent, 1);
	for (int i = 0; i < RING_DOTS; i++) {
		double turns;
		if (!ring_angle(t - i * RING_STAGGER, &turns)) {
			continue;
		}
		/* From the top, clockwise */
		double a = turns * 2 * M_PI - M_PI / 2;
		cairo_new_path(cr);
		cairo_arc(cr, cx + radius * cos(a), cy + radius * sin(a), dot, 0,
			2 * M_PI);
		cairo_fill(cr);
	}
}

static bool ring_tick(struct c8ui_widget *w, int64_t now) {
	struct ring *r = w->data;
	c8ui_widget_queue_draw(w);
	return r->active && c8ui_widget_is_shown(w);
}

static void free_data(struct c8ui_widget *w) {
	free(w->data);
}

static const struct c8ui_widget_impl ring_impl = {
	.name = "ring",
	.measure = ring_measure,
	.draw = ring_draw,
	.tick = ring_tick,
	.destroy = free_data,
};

struct c8ui_widget *c8ui_ring_new(double size) {
	struct ring *r = calloc(1, sizeof(*r));
	r->size = size > 0 ? size : 28;
	r->active = true;
	return c8ui_widget_new(&ring_impl, r);
}

void c8ui_ring_set_active(struct c8ui_widget *w, bool active) {
	struct ring *r = w->data;
	if (active && !r->active) {
		r->start = 0;
	}
	r->active = active;
	c8ui_widget_queue_draw(w);
}

/* Picture */

struct image {
	cairo_surface_t *surface;
	double width, height;
	enum c8ui_fit fit;
};

static void image_size(struct image *im, double *w, double *h) {
	*w = *h = 0;
	if (im->surface && cairo_surface_get_type(im->surface) ==
			CAIRO_SURFACE_TYPE_IMAGE) {
		*w = cairo_image_surface_get_width(im->surface);
		*h = cairo_image_surface_get_height(im->surface);
	}
}

static void image_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct image *im = w->data;
	double iw, ih;
	image_size(im, &iw, &ih);
	/* Both sides given, or no picture to take a shape from */
	if ((im->width > 0 && im->height > 0) || iw <= 0 || ih <= 0) {
		*width = im->width;
		*height = im->height;
		return;
	}
	/* One side given: the other keeps the shape */
	if (im->width > 0) {
		*width = im->width;
		*height = ih * im->width / iw;
	} else if (im->height > 0) {
		*height = im->height;
		*width = iw * im->height / ih;
	} else {
		*width = iw;
		*height = ih;
	}
	if (*width > avail && avail > 0) {
		*height *= avail / *width;
		*width = avail;
	}
}

static void image_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct image *im = w->data;
	double iw, ih;
	image_size(im, &iw, &ih);
	if (iw <= 0 || ih <= 0 || w->rect.width <= 0 || w->rect.height <= 0) {
		return;
	}
	struct c8ui_rect r = w->rect;
	double sx = r.width / iw, sy = r.height / ih;
	double scale = im->fit == C8UI_FIT_COVER ? fmax(sx, sy) : fmin(sx, sy);
	double dw = iw * scale, dh = ih * scale;
	cairo_save(cr);
	cairo_rectangle(cr, r.x, r.y, r.width, r.height);
	cairo_clip(cr);
	/* Shrunk once, then copied (kept.c) */
	c8ui_draw_surface(cr, im->surface, r.x + (r.width - dw) / 2,
		r.y + (r.height - dh) / 2, dw, dh);
	cairo_restore(cr);
}

static void image_destroy(struct c8ui_widget *w) {
	struct image *im = w->data;
	if (im->surface) {
		cairo_surface_destroy(im->surface);
	}
	free(im);
}

static const struct c8ui_widget_impl image_impl = {
	.name = "image",
	.measure = image_measure,
	.draw = image_draw,
	.destroy = image_destroy,
};

struct c8ui_widget *c8ui_image_new(cairo_surface_t *surface, double width,
		double height) {
	struct image *im = calloc(1, sizeof(*im));
	im->width = width;
	im->height = height;
	struct c8ui_widget *w = c8ui_widget_new(&image_impl, im);
	c8ui_image_set(w, surface);
	return w;
}

void c8ui_image_set(struct c8ui_widget *w, cairo_surface_t *surface) {
	struct image *im = w->data;
	if (surface) {
		cairo_surface_reference(surface);
	}
	if (im->surface) {
		cairo_surface_destroy(im->surface);
	}
	im->surface = surface;
	c8ui_widget_queue_layout(w);
}

void c8ui_image_set_fit(struct c8ui_widget *w, enum c8ui_fit fit) {
	((struct image *)w->data)->fit = fit;
	c8ui_widget_queue_draw(w);
}

/* Round buttons: a command in a circle, like the app bar's, and the back
 * button */

#define CIRCLE 40
#define RING 2
#define GLYPH 20
#define ROUND_LABEL_W 80

struct round {
	char *label; // under the circle, or NULL
	struct c8ui_icon *icon;
	bool back; // draws the arrow
	bool toggle, on;
	c8ui_action_fn fn;
	void *data;
};

static void round_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct round *r = w->data;
	*width = CIRCLE;
	*height = CIRCLE;
	if (r->label) {
		double tw, th;
		c8ui_text_size(c8ui_widget_font(w),
			c8ui_text_font(C8UI_TEXT_CAPTION), r->label, ROUND_LABEL_W, 2,
			&tw, &th);
		*width = ROUND_LABEL_W;
		*height += 5 + th;
	}
}

static void round_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct round *r = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	double alpha = w->disabled ? 0.4 : 1;
	double cx = w->rect.x + w->rect.width / 2;
	double cy = w->rect.y + CIRCLE / 2.0;
	bool down = (w->pressed && w->hovered) || r->on;

	cairo_new_path(cr);
	cairo_arc(cr, cx, cy, CIRCLE / 2.0 - RING / 2.0, 0, 2 * M_PI);
	if (down) {
		c8ui_set_source(cr, c.fg, alpha);
		cairo_fill_preserve(cr);
	} else if (w->hovered && !w->disabled) {
		c8ui_set_source(cr, c.fg, c.fill * 1.5);
		cairo_fill_preserve(cr);
	}
	c8ui_set_source(cr, c.fg, alpha);
	cairo_set_line_width(cr, RING);
	cairo_stroke(cr);

	uint32_t glyph = down ? c.bg : c.fg;
	if (r->back) {
		/* An arrow pointing left */
		c8ui_set_source(cr, glyph, alpha);
		cairo_set_line_width(cr, 2);
		cairo_move_to(cr, cx + 8, cy);
		cairo_line_to(cr, cx - 8, cy);
		cairo_stroke(cr);
		cairo_move_to(cr, cx - 1, cy - 7);
		cairo_line_to(cr, cx - 8, cy);
		cairo_line_to(cr, cx - 1, cy + 7);
		cairo_stroke(cr);
	} else if (r->icon) {
		c8ui_icon_draw_tinted(cr, r->icon, cx, cy, GLYPH, glyph, alpha);
	} else {
		/* No icon: the first letter of the label or tooltip stands in */
		const char *text = r->label ? r->label : w->tooltip;
		if (text && text[0]) {
			char first[8] = { 0 };
			size_t n = 1;
			while (text[n] && ((unsigned char)text[n] & 0xc0) == 0x80) {
				n++;
			}
			memcpy(first, text, n < sizeof(first) ? n : sizeof(first) - 1);
			struct c8ui_font f = c8ui_text_font(C8UI_TEXT_TITLE);
			double tw, th;
			c8ui_text_size(c8ui_widget_font(w), f, first, 0, 0, &tw, &th);
			c8ui_set_source(cr, glyph, alpha);
			c8ui_text_draw(cr, c8ui_widget_font(w), f, first, cx - tw / 2,
				cy - th / 2, 0, 0);
		}
	}

	if (r->label) {
		struct c8ui_font f = c8ui_text_font(C8UI_TEXT_CAPTION);
		double tw, th;
		c8ui_text_size(c8ui_widget_font(w), f, r->label, w->rect.width, 2,
			&tw, &th);
		c8ui_set_source(cr, c.fg, alpha);
		c8ui_text_draw(cr, c8ui_widget_font(w), f, r->label,
			w->rect.x + (w->rect.width - tw) / 2, cy + CIRCLE / 2.0 + 5,
			w->rect.width, 2);
	}
}

static void round_activate(struct c8ui_widget *w) {
	struct round *r = w->data;
	if (r->toggle) {
		r->on = !r->on;
		c8ui_widget_queue_draw(w);
	}
	if (r->fn) {
		r->fn(w, r->data);
	}
}

void c8ui_back_activate(struct c8ui_widget *w) {
	round_activate(w);
}

static bool round_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	return c8ui_push_event(w, ev, round_activate);
}

static void round_destroy(struct c8ui_widget *w) {
	struct round *r = w->data;
	if (r->back && w->root && w->root->back == w) {
		c8ui_root_set_back(w->root, NULL);
	}
	free(r->label);
	c8ui_icon_destroy(r->icon);
	free(r);
}

static void round_layout(struct c8ui_widget *w) {
	struct round *r = w->data;
	/* Once it is in a window, it answers Alt+Left there */
	if (r->back && w->root && w->root->back == NULL) {
		c8ui_root_set_back(w->root, w);
	}
}

static const struct c8ui_widget_impl round_impl = {
	.name = "round-button",
	.measure = round_measure,
	.layout = round_layout,
	.draw = round_draw,
	.event = round_event,
	.destroy = round_destroy,
};

struct c8ui_widget *c8ui_icon_button_new(const char *icon, const char *label,
		c8ui_action_fn fn, void *data) {
	struct round *r = calloc(1, sizeof(*r));
	bool has_label = label && label[0];
	r->label = has_label ? strdup(label) : NULL;
	r->icon = icon && icon[0] ? c8ui_icon_load(NULL, icon) : NULL;
	r->fn = fn;
	r->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&round_impl, r);
	w->focusable = true;
	return w;
}

void c8ui_icon_button_set_toggle(struct c8ui_widget *w, bool on) {
	struct round *r = w->data;
	r->toggle = true;
	r->on = on;
	c8ui_widget_queue_draw(w);
}

bool c8ui_icon_button_get_toggle(struct c8ui_widget *w) {
	return ((struct round *)w->data)->on;
}

struct c8ui_widget *c8ui_back_button_new(c8ui_action_fn fn, void *data) {
	struct round *r = calloc(1, sizeof(*r));
	r->back = true;
	r->fn = fn;
	r->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&round_impl, r);
	w->focusable = true;
	c8ui_widget_set_tooltip(w, "Back");
	return w;
}
