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

/* Small things from the Windows 8 samples that c8ui lacked: a button that
 * stays down, one that repeats, a block of content that can be selected,
 * and a scaled picture of a widget. */

#define CONTROL_HEIGHT 36
#define BORDER 2
#define DRAG_START 8
#define CHECK_SIZE 26

static void draw_label(struct c8ui_widget *w, cairo_t *cr, const char *text,
		uint32_t color, double alpha) {
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY_STRONG);
	double tw, th;
	c8ui_text_size(c8ui_widget_font(w), font, text, 0, 0, &tw, &th);
	c8ui_set_source(cr, color, alpha);
	c8ui_text_draw(cr, c8ui_widget_font(w), font, text,
		w->rect.x + (w->rect.width - tw) / 2,
		w->rect.y + (w->rect.height - th) / 2, w->rect.width, 1);
}

static void label_measure(struct c8ui_widget *w, const char *text,
		double *width, double *height) {
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY_STRONG);
	double tw, th;
	c8ui_text_size(c8ui_widget_font(w), font, text, 0, 0, &tw, &th);
	*width = tw + 32 < 48 ? 48 : tw + 32;
	*height = CONTROL_HEIGHT;
}

/* Toggle button */

struct toggle_button {
	char *label;
	bool on;
	c8ui_action_fn fn;
	void *data;
};

static void togglebutton_measure(struct c8ui_widget *w, double avail,
		double *width, double *height) {
	struct toggle_button *b = w->data;
	label_measure(w, b->label, width, height);
}

static void togglebutton_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct toggle_button *b = w->data;
	draw_label(w, cr, b->label, c8ui_button_face(w, cr, b->on),
		w->disabled ? 0.4 : 1);
}

static void togglebutton_flip(struct c8ui_widget *w) {
	struct toggle_button *b = w->data;
	b->on = !b->on;
	c8ui_widget_queue_draw(w);
	if (b->fn) {
		b->fn(w, b->data);
	}
}

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

static void togglebutton_destroy(struct c8ui_widget *w) {
	struct toggle_button *b = w->data;
	free(b->label);
	free(b);
}

static const struct c8ui_widget_impl togglebutton_impl = {
	.name = "toggle-button",
	.measure = togglebutton_measure,
	.draw = togglebutton_draw,
	.event = togglebutton_event,
	.destroy = togglebutton_destroy,
};

struct c8ui_widget *c8ui_togglebutton_new(const char *label, bool on,
		c8ui_action_fn fn, void *data) {
	struct toggle_button *b = calloc(1, sizeof(*b));
	b->label = strdup(label ? label : "");
	b->on = on;
	b->fn = fn;
	b->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&togglebutton_impl, b);
	w->focusable = true;
	return w;
}

bool c8ui_togglebutton_get(struct c8ui_widget *w) {
	return ((struct toggle_button *)w->data)->on;
}

void c8ui_togglebutton_set(struct c8ui_widget *w, bool on) {
	((struct toggle_button *)w->data)->on = on;
	c8ui_widget_queue_draw(w);
}

/* Repeat button */

#define REPEAT_FIRST 450 // ms held before it starts repeating
#define REPEAT_SLOW 110
#define REPEAT_FAST 40
#define REPEAT_STEP 6 // repeats between speeding up

struct repeat_button {
	char *label;
	c8ui_action_fn fn;
	void *data;
	void *timer;
	int repeats;
	int delay;
	bool held;
};

static void repeat_stop(struct c8ui_widget *w) {
	struct repeat_button *b = w->data;
	if (b->timer && w->root) {
		c8ui_root_timer_remove(w->root, b->timer);
	}
	b->timer = NULL;
	b->held = false;
}

static int repeat_tick(void *data) {
	struct c8ui_widget *w = data;
	struct repeat_button *b = w->data;
	if (!b->held || w->disabled) {
		b->timer = NULL;
		b->held = false;
		return 0;
	}
	/* Out of the button, the pointer stops it; back in, it goes on */
	if (!w->hovered) {
		return b->delay;
	}
	if (++b->repeats % REPEAT_STEP == 0 && b->delay > REPEAT_FAST) {
		b->delay = b->delay * 3 / 4 < REPEAT_FAST ? REPEAT_FAST :
			b->delay * 3 / 4;
	}
	int delay = b->delay;
	if (b->fn) {
		b->fn(w, b->data);
	}
	/* fn must not destroy the button: it is a stepper, not a closer */
	return delay;
}

static void repeat_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct repeat_button *b = w->data;
	label_measure(w, b->label, width, height);
}

static void repeat_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct repeat_button *b = w->data;
	draw_label(w, cr, b->label, c8ui_button_face(w, cr, false),
		w->disabled ? 0.4 : 1);
}

static bool repeat_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct repeat_button *b = w->data;
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		if (ev->button != C8UI_BUTTON_LEFT) {
			return false;
		}
		repeat_stop(w);
		b->held = true;
		b->repeats = 0;
		b->delay = REPEAT_SLOW;
		if (b->fn) {
			b->fn(w, b->data);
		}
		/* fn may have taken the button away */
		if (w->root && b->held) {
			b->timer = c8ui_root_timer_add(w->root, REPEAT_FIRST, repeat_tick, w);
		}
		return true;
	case C8UI_EVENT_RELEASE:
	case C8UI_EVENT_TOUCH_CANCEL:
		repeat_stop(w);
		c8ui_widget_queue_draw(w);
		return true;
	case C8UI_EVENT_KEY:
		/* The keyboard repeats by itself */
		if (c8ui_activates(ev)) {
			if (b->fn) {
				b->fn(w, b->data);
			}
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void repeat_destroy(struct c8ui_widget *w) {
	struct repeat_button *b = w->data;
	repeat_stop(w);
	free(b->label);
	free(b);
}

static const struct c8ui_widget_impl repeat_impl = {
	.name = "repeat-button",
	.measure = repeat_measure,
	.draw = repeat_draw,
	.event = repeat_event,
	.destroy = repeat_destroy,
};

struct c8ui_widget *c8ui_repeat_button_new(const char *label,
		c8ui_action_fn fn, void *data) {
	struct repeat_button *b = calloc(1, sizeof(*b));
	b->label = strdup(label ? label : "");
	b->fn = fn;
	b->data = data;
	struct c8ui_widget *w = c8ui_widget_new(&repeat_impl, b);
	w->focusable = true;
	return w;
}

void c8ui_repeat_button_set_label(struct c8ui_widget *w, const char *label) {
	struct repeat_button *b = w->data;
	free(b->label);
	b->label = strdup(label ? label : "");
	c8ui_widget_queue_layout(w);
}

/* Item container */

struct item_container {
	enum c8ui_item_tap tap;
	bool selectable;
	bool selected;
	double press_x, press_y;
	bool dragging;
	c8ui_action_fn invoke_fn;
	void *invoke_data;
	c8ui_action_fn select_fn;
	void *select_data;
	c8ui_action_fn drag_fn;
	void *drag_data;
};

static void item_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	if (w->child_count == 0) {
		*width = *height = 0;
		return;
	}
	c8ui_widget_measure(w->children[0], avail, width, height);
}

static void item_layout(struct c8ui_widget *w) {
	if (w->child_count > 0) {
		c8ui_widget_layout(w->children[0], w->rect);
	}
}

static void item_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct item_container *ic = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	if (!ic->selected && (w->hovered || w->pressed) && !w->disabled) {
		c8ui_set_source(cr, c.fg, w->pressed && w->hovered ? c.fill * 2 :
			c.fill);
		cairo_rectangle(cr, w->rect.x, w->rect.y, w->rect.width,
			w->rect.height);
		cairo_fill(cr);
	}
}

static void item_draw_over(struct c8ui_widget *w, cairo_t *cr) {
	struct item_container *ic = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	struct c8ui_rect r = w->rect;
	if (ic->selected) {
		c8ui_set_source(cr, c.accent, 1);
		c8ui_stroke_rect(cr, r.x, r.y, r.width, r.height, 3);
		double x = r.x + r.width, y = r.y;
		cairo_move_to(cr, x - CHECK_SIZE * 1.4, y);
		cairo_line_to(cr, x, y);
		cairo_line_to(cr, x, y + CHECK_SIZE * 1.4);
		cairo_close_path(cr);
		cairo_fill(cr);
		cairo_set_source_rgb(cr, 1, 1, 1);
		cairo_set_line_width(cr, 2);
		cairo_move_to(cr, x - 15, y + 9);
		cairo_line_to(cr, x - 11, y + 13);
		cairo_line_to(cr, x - 4, y + 5);
		cairo_stroke(cr);
	} else if (w->hovered && ic->selectable && !w->disabled) {
		c8ui_set_source(cr, c.fg, c.border_hover);
		c8ui_stroke_rect(cr, r.x, r.y, r.width, r.height, 2);
	}
	if (w->focused && w->root && w->root->focus_visible) {
		c8ui_set_source(cr, c.fg, 1);
		c8ui_dotted_rect(cr, r.x + 2.5, r.y + 2.5, r.width - 5, r.height - 5);
	}
}

static void item_set_selected(struct c8ui_widget *w, bool selected, bool notify) {
	struct item_container *ic = w->data;
	if (ic->selected == selected) {
		return;
	}
	ic->selected = selected;
	c8ui_widget_queue_draw(w);
	if (notify && ic->select_fn) {
		ic->select_fn(w, ic->select_data);
	}
}

static void item_tap(struct c8ui_widget *w) {
	struct item_container *ic = w->data;
	switch (ic->tap) {
	case C8UI_ITEM_TAP_SELECT:
		if (ic->selectable) {
			item_set_selected(w, !ic->selected, true);
		}
		if (ic->invoke_fn) {
			ic->invoke_fn(w, ic->invoke_data);
		}
		break;
	case C8UI_ITEM_TAP_INVOKE:
		if (ic->invoke_fn) {
			ic->invoke_fn(w, ic->invoke_data);
		}
		break;
	case C8UI_ITEM_TAP_NONE:
		break;
	}
}

static bool item_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct item_container *ic = w->data;
	if (w->disabled) {
		return false;
	}
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		if (ev->button == C8UI_BUTTON_RIGHT) {
			/* A hold on a touchscreen comes as this: the way to select
			 * when a tap invokes */
			if (ic->selectable) {
				item_set_selected(w, !ic->selected, true);
			}
			return true;
		}
		if (ev->button != C8UI_BUTTON_LEFT) {
			return false;
		}
		ic->press_x = ev->x;
		ic->press_y = ev->y;
		ic->dragging = false;
		return true;
	case C8UI_EVENT_MOTION:
		if (w->pressed && !ic->dragging && ic->drag_fn &&
				hypot(ev->x - ic->press_x, ev->y - ic->press_y) > DRAG_START) {
			ic->dragging = true;
			ic->drag_fn(w, ic->drag_data);
			return true;
		}
		return false;
	case C8UI_EVENT_RELEASE:
		if (!ic->dragging && c8ui_rect_contains(&w->rect, ev->x, ev->y)) {
			if ((ev->mods & C8UI_MOD_CTRL) && ic->selectable) {
				item_set_selected(w, !ic->selected, true);
			} else {
				item_tap(w);
			}
		}
		ic->dragging = false;
		return true;
	case C8UI_EVENT_KEY:
		if (c8ui_activates(ev) && ev->sym == XKB_KEY_space && ic->selectable) {
			item_set_selected(w, !ic->selected, true);
			return true;
		}
		if (c8ui_activates(ev) && ev->sym != XKB_KEY_space) {
			if (ic->invoke_fn) {
				ic->invoke_fn(w, ic->invoke_data);
			}
			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 item_destroy(struct c8ui_widget *w) {
	free(w->data);
}

static const struct c8ui_widget_impl item_impl = {
	.name = "item-container",
	.measure = item_measure,
	.layout = item_layout,
	.draw = item_draw,
	.draw_over = item_draw_over,
	.event = item_event,
	.destroy = item_destroy,
};

struct c8ui_widget *c8ui_item_container_new(struct c8ui_widget *child) {
	struct item_container *ic = calloc(1, sizeof(*ic));
	ic->tap = C8UI_ITEM_TAP_SELECT;
	ic->selectable = true;
	struct c8ui_widget *w = c8ui_widget_new(&item_impl, ic);
	w->focusable = true;
	w->tilts = true; // an item pressed as a whole, as a tile is
	w->cursor = C8UI_CURSOR_POINTER;
	if (child) {
		c8ui_widget_add(w, child);
	}
	return w;
}

void c8ui_item_container_set_tap(struct c8ui_widget *w,
		enum c8ui_item_tap tap) {
	((struct item_container *)w->data)->tap = tap;
}

void c8ui_item_container_set_selectable(struct c8ui_widget *w, bool selectable) {
	struct item_container *ic = w->data;
	ic->selectable = selectable;
	if (!selectable) {
		item_set_selected(w, false, false);
	}
}

bool c8ui_item_container_get_selected(struct c8ui_widget *w) {
	return ((struct item_container *)w->data)->selected;
}

void c8ui_item_container_set_selected(struct c8ui_widget *w, bool selected) {
	struct item_container *ic = w->data;
	if (ic->selectable) {
		item_set_selected(w, selected, false);
	}
}

void c8ui_item_container_on_invoke(struct c8ui_widget *w, c8ui_action_fn fn,
		void *data) {
	struct item_container *ic = w->data;
	ic->invoke_fn = fn;
	ic->invoke_data = data;
}

void c8ui_item_container_on_select(struct c8ui_widget *w, c8ui_action_fn fn,
		void *data) {
	struct item_container *ic = w->data;
	ic->select_fn = fn;
	ic->select_data = data;
}

void c8ui_item_container_on_drag(struct c8ui_widget *w, c8ui_action_fn fn,
		void *data) {
	struct item_container *ic = w->data;
	ic->drag_fn = fn;
	ic->drag_data = data;
}

/* Viewbox */

/* The child is laid out at its own size, a long way off to the side so no
 * pointer or finger can reach it, and drawn shrunk or grown to fit. */
#define VIEWBOX_FAR 1000000.0

struct viewbox {
	double cw, ch; // the child's own size
	double scale;
	bool grow;
};

static void viewbox_child_size(struct c8ui_widget *w, double *cw, double *ch) {
	double nw, nh;
	if (w->child_count == 0) {
		*cw = *ch = 0;
		return;
	}
	struct c8ui_widget *c = w->children[0];
	c8ui_widget_measure(c, 1e4, &nw, &nh);
	*cw = c->fixed_width > 0 ? c->fixed_width : nw;
	*ch = c->fixed_height > 0 ? c->fixed_height : nh;
}

static void viewbox_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct viewbox *v = w->data;
	double cw, ch;
	viewbox_child_size(w, &cw, &ch);
	double s = cw > 0 && cw > avail ? avail / cw : 1;
	if (cw > 0 && v->grow) {
		s = avail / cw;
	}
	*width = cw * s;
	*height = ch * s;
}

static void viewbox_layout(struct c8ui_widget *w) {
	struct viewbox *v = w->data;
	if (w->child_count == 0) {
		return;
	}
	viewbox_child_size(w, &v->cw, &v->ch);
	double sx = v->cw > 0 ? w->rect.width / v->cw : 1;
	double sy = v->ch > 0 ? w->rect.height / v->ch : 1;
	v->scale = sx < sy ? sx : sy;
	if (!v->grow && v->scale > 1) {
		v->scale = 1;
	}
	c8ui_widget_layout(w->children[0], (struct c8ui_rect){
		w->rect.x + VIEWBOX_FAR, w->rect.y, v->cw, v->ch });
}

static void viewbox_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct viewbox *v = w->data;
	/* The children are drawn after this, with whatever is set here */
	cairo_rectangle(cr, w->rect.x, w->rect.y, w->rect.width, w->rect.height);
	cairo_clip(cr);
	double ox = w->rect.x + (w->rect.width - v->cw * v->scale) / 2;
	double oy = w->rect.y + (w->rect.height - v->ch * v->scale) / 2;
	cairo_translate(cr, ox, oy);
	cairo_scale(cr, v->scale, v->scale);
	cairo_translate(cr, -(w->rect.x + VIEWBOX_FAR), -w->rect.y);
}

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

static const struct c8ui_widget_impl viewbox_impl = {
	.name = "viewbox",
	.measure = viewbox_measure,
	.layout = viewbox_layout,
	.draw = viewbox_draw,
	.destroy = viewbox_destroy,
};

struct c8ui_widget *c8ui_viewbox_new(struct c8ui_widget *child) {
	struct viewbox *v = calloc(1, sizeof(*v));
	v->scale = 1;
	struct c8ui_widget *w = c8ui_widget_new(&viewbox_impl, v);
	w->moves_children = true;
	if (child) {
		c8ui_widget_add(w, child);
	}
	return w;
}

void c8ui_viewbox_set_grow(struct c8ui_widget *w, bool grow) {
	((struct viewbox *)w->data)->grow = grow;
	c8ui_widget_queue_layout(w);
}
