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

/* The app bar: a dark band along the bottom with round command buttons,
 * the contextual ones on the left and the ones always there on the
 * right. It is an overlay while shown, so a click anywhere else only
 * closes it. */

#define BAR_HEIGHT 88
#define BAR_PAD 20
#define COMMAND_WIDTH 80
#define CIRCLE 40
#define RING 2
#define GLYPH 20
#define SLIDE_MS 200
#define BAR_COLOR 0x1d1d1d

struct appbar {
	struct c8ui_widget *left, *right; // the two groups
	struct c8ui_root *root; // it belongs to
	bool shown, closing;
	int64_t start; // of the slide, 0: not started
	double from, shown_frac; // 0 hidden to 1 up
	double height; // BAR_HEIGHT, more when the commands wrap
};

struct command {
	char *label;
	struct c8ui_icon *icon;
	bool toggle, on;
	c8ui_action_fn fn;
	void *data;
	struct c8ui_widget *bar;
};

/* Commands */

static void command_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = COMMAND_WIDTH;
	*height = BAR_HEIGHT - 2 * 10;
}

static void command_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct command *cmd = w->data;
	struct c8ui_colors c = c8ui_widget_colors(w);
	struct c8ui_rect r = w->rect;
	double alpha = w->disabled ? 0.4 : 1;
	double cx = r.x + r.width / 2, cy = r.y + 4 + CIRCLE / 2;
	bool down = (w->pressed && w->hovered) || cmd->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 ? BAR_COLOR : c.fg;
	if (cmd->icon) {
		c8ui_icon_draw_tinted(cr, cmd->icon, cx, cy, GLYPH, glyph, alpha);
	} else if (cmd->label && cmd->label[0]) {
		/* No icon: the label's first letter stands in */
		char first[8] = { 0 };
		size_t n = 1;
		while (cmd->label[n] && ((unsigned char)cmd->label[n] & 0xc0) == 0x80) {
			n++;
		}
		memcpy(first, cmd->label, 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);
	}

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

static void command_activate(struct c8ui_widget *w) {
	struct command *cmd = w->data;
	if (cmd->toggle) {
		cmd->on = !cmd->on;
		c8ui_widget_queue_draw(w);
	}
	c8ui_action_fn fn = cmd->fn;
	void *data = cmd->data;
	/* Gone first, as in Metro; fn may show it again */
	c8ui_appbar_hide(cmd->bar);
	if (fn) {
		fn(w, data);
	}
}

static bool command_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		return ev->button == C8UI_BUTTON_LEFT;
	case C8UI_EVENT_RELEASE:
		if (c8ui_rect_contains(&w->rect, ev->x, ev->y)) {
			command_activate(w);
		}
		return true;
	case C8UI_EVENT_KEY:
		if (c8ui_activates(ev)) {
			command_activate(w);
			return true;
		}
		return false;
	case C8UI_EVENT_ENTER:
	case C8UI_EVENT_LEAVE:
		c8ui_widget_queue_draw(w);
		return false;
	default:
		return false;
	}
}

static void command_destroy(struct c8ui_widget *w) {
	struct command *cmd = w->data;
	free(cmd->label);
	c8ui_icon_destroy(cmd->icon);
	free(cmd);
}

static const struct c8ui_widget_impl command_impl = {
	.name = "appbar-command",
	.measure = command_measure,
	.draw = command_draw,
	.event = command_event,
	.destroy = command_destroy,
};

/* The bar */

static double bar_top(struct c8ui_widget *w) {
	struct appbar *a = w->data;
	return w->rect.y + w->rect.height - a->height * a->shown_frac;
}

/* One row, the two groups at either end; when they don't both fit (a
 * narrow window) the groups wrap into rows, the global ones on top */
static void bar_layout(struct c8ui_widget *w) {
	struct appbar *a = w->data;
	double room = w->rect.width - 2 * BAR_PAD;
	double gw, gh, lw, lh;
	c8ui_widget_measure(a->right, 1e5, &gw, &gh);
	c8ui_widget_measure(a->left, 1e5, &lw, &lh);
	bool one_row = gw + lw + (gw > 0 && lw > 0 ? BAR_PAD : 0) <= room;
	if (!one_row) {
		c8ui_widget_measure(a->right, room, &gw, &gh);
		c8ui_widget_measure(a->left, room, &lw, &lh);
	}
	/* Wrapped: room under the last row for two-line labels */
	a->height = one_row ? BAR_HEIGHT : 30 + gh + lh + (gh > 0 && lh > 0 ? 8 : 0);
	if (a->height < BAR_HEIGHT) {
		a->height = BAR_HEIGHT;
	}
	double y = bar_top(w) + 10;
	if (one_row) {
		c8ui_widget_layout(a->right, (struct c8ui_rect){
			w->rect.x + w->rect.width - BAR_PAD - gw, y, gw, gh });
		c8ui_widget_layout(a->left, (struct c8ui_rect){
			w->rect.x + BAR_PAD, y, lw, lh });
		return;
	}
	c8ui_widget_layout(a->right, (struct c8ui_rect){
		w->rect.x + BAR_PAD, y, room, gh });
	c8ui_widget_layout(a->left, (struct c8ui_rect){
		w->rect.x + BAR_PAD, y + gh + (gh > 0 ? 8 : 0), room, lh });
}

static void bar_draw(struct c8ui_widget *w, cairo_t *cr) {
	double y = bar_top(w);
	c8ui_set_source(cr, BAR_COLOR, 1);
	cairo_rectangle(cr, w->rect.x, y, w->rect.width, w->rect.y +
		w->rect.height - y);
	cairo_fill(cr);
}

static void bar_finish_hide(struct c8ui_widget *w) {
	struct appbar *a = w->data;
	a->shown = a->closing = false;
	c8ui_root_remove_overlay(a->root, w);
}

static bool bar_tick(struct c8ui_widget *w, int64_t now) {
	struct appbar *a = w->data;
	if (a->start == 0) {
		a->start = now;
	}
	double t = (double)(now - a->start) / SLIDE_MS;
	t = t > 1 ? 1 : t;
	double e = c8ui_ease_out(t);
	a->shown_frac = a->from + ((a->closing ? 0 : 1) - a->from) * e;
	c8ui_widget_queue_layout(w);
	if (t >= 1 && a->closing) {
		bar_finish_hide(w);
		return false;
	}
	return t < 1;
}

static bool bar_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	switch (ev->type) {
	case C8UI_EVENT_PRESS:
		/* Light dismiss: a click above the bar only closes it */
		if (ev->y < bar_top(w)) {
			c8ui_appbar_hide(w);
		}
		return true;
	case C8UI_EVENT_RELEASE:
	case C8UI_EVENT_MOTION:
	case C8UI_EVENT_SCROLL:
		return true;
	case C8UI_EVENT_TOUCH_DOWN:
		if (ev->y < bar_top(w)) {
			c8ui_appbar_hide(w);
			return true;
		}
		return false;
	case C8UI_EVENT_KEY:
		if (ev->sym == XKB_KEY_Escape) {
			c8ui_appbar_hide(w);
			return true;
		}
		/* Arrows go along the commands */
		if (ev->sym == XKB_KEY_Left || ev->sym == XKB_KEY_Right) {
			struct appbar *a = w->data;
			struct c8ui_widget *all[64];
			int n = 0, at = -1;
			struct c8ui_widget *groups[] = { a->left, a->right };
			for (int g = 0; g < 2; g++) {
				for (int i = 0; i < groups[g]->child_count && n < 64; i++) {
					struct c8ui_widget *c = groups[g]->children[i];
					if (c->hidden || c->disabled) {
						continue;
					}
					if (w->root && c == c8ui_root_focus(w->root)) {
						at = n;
					}
					all[n++] = c;
				}
			}
			if (n == 0) {
				return true;
			}
			at = at < 0 ? 0 : (at + (ev->sym == XKB_KEY_Right ? 1 : n - 1)) % n;
			c8ui_root_show_focus(w->root, true);
			c8ui_widget_grab_focus(all[at]);
			return true;
		}
		return false;
	default:
		return false;
	}
}

static void bar_destroy(struct c8ui_widget *w) {
	struct appbar *a = w->data;
	c8ui_root_unkeep(a->root, w);
	free(a);
}

static const struct c8ui_widget_impl bar_impl = {
	.name = "appbar",
	.layout = bar_layout,
	.draw = bar_draw,
	.event = bar_event,
	.tick = bar_tick,
	.destroy = bar_destroy,
};

struct c8ui_widget *c8ui_appbar_new(struct c8ui_root *root) {
	struct appbar *a = calloc(1, sizeof(*a));
	a->root = root;
	struct c8ui_widget *w = c8ui_widget_new(&bar_impl, a);
	w->scheme = C8UI_SCHEME_DARK;
	a->height = BAR_HEIGHT;
	a->left = c8ui_box_new(C8UI_HORIZONTAL, 0);
	a->right = c8ui_box_new(C8UI_HORIZONTAL, 0);
	c8ui_box_set_wrap(a->left, true);
	c8ui_box_set_wrap(a->right, true);
	c8ui_widget_add(w, a->left);
	c8ui_widget_add(w, a->right);
	c8ui_root_keep(root, w);
	return w;
}

struct c8ui_widget *c8ui_appbar_add(struct c8ui_widget *bar, const char *icon,
		const char *label, bool right, c8ui_action_fn fn, void *data) {
	struct appbar *a = bar->data;
	struct command *cmd = calloc(1, sizeof(*cmd));
	cmd->label = strdup(label ? label : "");
	cmd->icon = c8ui_icon_load(NULL, icon);
	cmd->fn = fn;
	cmd->data = data;
	cmd->bar = bar;
	struct c8ui_widget *w = c8ui_widget_new(&command_impl, cmd);
	w->focusable = true;
	w->cursor = C8UI_CURSOR_POINTER;
	c8ui_widget_add(right ? a->right : a->left, w);
	return w;
}

void c8ui_appbar_command_set_toggle(struct c8ui_widget *w, bool on) {
	struct command *cmd = w->data;
	cmd->toggle = true;
	cmd->on = on;
	c8ui_widget_queue_draw(w);
}

bool c8ui_appbar_command_get_toggle(struct c8ui_widget *w) {
	return ((struct command *)w->data)->on;
}

void c8ui_appbar_show(struct c8ui_widget *w) {
	struct appbar *a = w->data;
	if (a->shown && !a->closing) {
		return;
	}
	if (!a->shown) {
		a->shown = true;
		a->shown_frac = 0;
		c8ui_root_push_overlay(a->root, w);
	}
	/* From wherever it is, if caught sliding away */
	a->from = a->shown_frac;
	a->closing = false;
	a->start = 0;
	c8ui_widget_animate(w);
}

void c8ui_appbar_hide(struct c8ui_widget *w) {
	struct appbar *a = w->data;
	if (!a->shown || a->closing) {
		return;
	}
	a->from = a->shown_frac;
	a->closing = true;
	a->start = 0;
	c8ui_widget_animate(w);
}

void c8ui_appbar_toggle(struct c8ui_widget *w) {
	if (c8ui_appbar_is_shown(w)) {
		c8ui_appbar_hide(w);
	} else {
		c8ui_appbar_show(w);
	}
}

bool c8ui_appbar_is_shown(struct c8ui_widget *w) {
	struct appbar *a = w->data;
	return a->shown && !a->closing;
}
