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

/*
 * Miller columns: each column opens the next at its right (a feed, then
 * the post chosen in it, then a reply chosen in that), so the way here
 * stays in sight. Opening from a column takes away the ones after it.
 * Wide, the columns pan sideways like a hub's sections, the newest
 * brought into view; narrow, only the last one shows, the window's
 * width, and back steps out of it.
 */

#define MILLER_EDGE 60 // left of the first, right of the last
#define MILLER_GAP 40 // between columns, a hairline down the middle
#define MILLER_MARGIN 40 // kept in sight beside a column it pans to
#define MILLER_FLING_MS 320

struct miller {
	double *widths;
	int count;
	int base; // columns back never takes away
	bool narrow;
	double offset, target, content;
	double edge, gap, top, bottom;
	struct c8ui_drag drag;
	double drag_offset;
	struct c8ui_pad pad;
	c8ui_miller_fn fn;
	void *data;
};

static void shift_x(struct c8ui_widget *w, double dx) {
	w->rect.x += dx;
	for (int i = 0; i < w->child_count; i++) {
		shift_x(w->children[i], dx);
	}
}

/* How far along the columns column i starts */
static double col_pos(struct miller *m, int i) {
	double pos = 0;
	for (int j = 0; j < i; j++) {
		pos += m->widths[j] + m->gap;
	}
	return pos;
}

static double miller_max(struct c8ui_widget *w) {
	struct miller *m = w->data;
	double max = m->content - w->rect.width;
	return m->narrow || max < 0 ? 0 : max;
}

static void miller_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	*width = avail;
	*height = 0; // as tall as it is given
}

static void miller_layout(struct c8ui_widget *w) {
	struct miller *m = w->data;
	double top = w->rect.y + m->top;
	double height = fmax(w->rect.height - m->top - m->bottom, 0);
	if (m->narrow) {
		/* One at a time: the last, across the window */
		m->content = w->rect.width;
		m->offset = m->target = 0;
		for (int i = 0; i < w->child_count; i++) {
			struct c8ui_widget *c = w->children[i];
			c->hidden = i != w->child_count - 1;
			c8ui_widget_layout(c, (struct c8ui_rect){ w->rect.x, top,
				w->rect.width, height });
		}
		return;
	}
	m->content = 2 * m->edge + (m->count ? col_pos(m, m->count - 1) +
		m->widths[m->count - 1] : 0);
	double max = miller_max(w);
	m->offset = fmin(m->offset, max);
	m->target = fmin(m->target, max);
	for (int i = 0; i < w->child_count && i < m->count; i++) {
		struct c8ui_widget *c = w->children[i];
		c->hidden = false;
		c8ui_widget_layout(c, (struct c8ui_rect){
			w->rect.x + m->edge - m->offset + col_pos(m, i), top,
			m->widths[i], height });
	}
}

static void set_offset(struct c8ui_widget *w, double offset) {
	struct miller *m = w->data;
	double max = miller_max(w);
	offset = offset < 0 ? 0 : offset > max ? max : offset;
	if (offset == m->offset) {
		return;
	}
	for (int i = 0; i < w->child_count; i++) {
		shift_x(w->children[i], m->offset - offset);
	}
	m->offset = offset;
	c8ui_widget_queue_draw(w);
}

static bool miller_tick(struct c8ui_widget *w, int64_t now) {
	struct miller *m = w->data;
	double d = m->target - m->offset;
	if (fabs(d) < 0.5) {
		set_offset(w, m->target);
		return false;
	}
	set_offset(w, m->offset + d * 0.3);
	return true;
}

/* to: where the pan should end up, held to the ends */
static void pan_to(struct c8ui_widget *w, double to, bool smooth) {
	struct miller *m = w->data;
	double max = miller_max(w);
	m->target = to < 0 ? 0 : to > max ? max : to;
	if (smooth) {
		c8ui_widget_animate(w);
	} else {
		set_offset(w, m->target);
	}
}

/* Column i in sight, from its left edge to its right if it fits */
static void show_column(struct c8ui_widget *w, int i) {
	struct miller *m = w->data;
	if (m->narrow || i < 0 || i >= m->count || w->rect.width <= 0) {
		return;
	}
	double left = m->edge + col_pos(m, i);
	double right = left + m->widths[i] + m->edge;
	double to = m->target;
	if (right - to > w->rect.width) {
		to = right - w->rect.width;
	}
	if (left - m->edge < to) {
		to = left - m->edge;
	}
	/* The pan's end is known before the next layout: content changed */
	m->content = 2 * m->edge + col_pos(m, m->count - 1) +
		m->widths[m->count - 1];
	pan_to(w, to, true);
}

static void miller_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct miller *m = w->data;
	if (m->narrow) {
		return;
	}
	/* A hairline in each gap: the columns read as one path */
	struct c8ui_colors c = c8ui_widget_colors(w);
	c8ui_set_source(cr, c.fg, 0.12);
	for (int i = 1; i < m->count; i++) {
		double x = round(w->rect.x + m->edge - m->offset + col_pos(m, i) -
			m->gap / 2) + 0.5;
		cairo_move_to(cr, x, w->rect.y + m->top);
		cairo_line_to(cr, x, w->rect.y + w->rect.height - m->bottom);
	}
	cairo_set_line_width(cr, 1);
	cairo_stroke(cr);
}

static void miller_draw_over(struct c8ui_widget *w, cairo_t *cr) {
	struct miller *m = w->data;
	double max = miller_max(w);
	if (max <= 1) {
		return;
	}
	/* A thin indicator along the bottom, as the hub's */
	struct c8ui_colors c = c8ui_widget_colors(w);
	double len = fmax(w->rect.width * w->rect.width / m->content, 24);
	double x = w->rect.x + (w->rect.width - len) * m->offset / max;
	c8ui_set_source(cr, c.fg, w->hovered ? 0.4 : 0.2);
	cairo_rectangle(cr, x, w->rect.y + w->rect.height - 6, len, 4);
	cairo_fill(cr);
}

static bool miller_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct miller *m = w->data;
	switch (ev->type) {
	case C8UI_EVENT_TOUCH_DOWN:
		if (miller_max(w) <= 0 || m->drag.down) {
			return false;
		}
		m->target = m->offset;
		m->drag_offset = m->offset;
		/* fall through */
	case C8UI_EVENT_TOUCH_MOTION:
	case C8UI_EVENT_TOUCH_UP:
	case C8UI_EVENT_TOUCH_CANCEL:
		switch (c8ui_drag_touch(w, &m->drag, ev)) {
		case C8UI_DRAG_IGNORED:
			return false;
		case C8UI_DRAG_START:
		case C8UI_DRAG_MOVE:
			set_offset(w, m->drag_offset - m->drag.delta);
			m->target = m->offset;
			return true;
		case C8UI_DRAG_END:
			pan_to(w, m->offset - m->drag.velocity * MILLER_FLING_MS, true);
			return true;
		default:
			return true;
		}
	case C8UI_EVENT_SCROLL: {
		/* Sideways only, or Shift: up and down belong to the columns,
		 * which are mostly lists */
		double d = ev->dx != 0 ? ev->dx :
			ev->mods & C8UI_MOD_SHIFT ? ev->dy : 0;
		if (d == 0 || miller_max(w) <= 0) {
			return false;
		}
		if (ev->precise) {
			c8ui_pad_sample(&m->pad, d, 0);
		} else {
			c8ui_pad_reset(&m->pad);
		}
		pan_to(w, (ev->precise ? m->offset : m->target) + d, !ev->precise);
		return true;
	}
	case C8UI_EVENT_SCROLL_STOP: {
		double vx, vy;
		if (miller_max(w) <= 0 || !c8ui_pad_lift(&m->pad, &vx, &vy) ||
				vx == 0) {
			return false;
		}
		pan_to(w, m->target + c8ui_pad_distance(vx), true);
		return true;
	}
	case C8UI_EVENT_KEY:
		/* Back out of the last one, from wherever the keyboard is in it */
		if ((ev->sym == XKB_KEY_Escape || ev->sym == XKB_KEY_BackSpace) &&
				!(ev->mods & ~C8UI_MOD_SHIFT)) {
			return c8ui_miller_back(w);
		}
		return false;
	default:
		return false;
	}
}

static void miller_reveal(struct c8ui_widget *w, const struct c8ui_rect *r) {
	struct miller *m = w->data;
	if (m->narrow) {
		return;
	}
	double left = r->x + (m->offset - m->target) - w->rect.x;
	double right = left + r->width;
	if (left < MILLER_MARGIN) {
		pan_to(w, m->target + left - MILLER_MARGIN, true);
	} else if (right > w->rect.width - MILLER_MARGIN) {
		double by = right - w->rect.width + MILLER_MARGIN;
		pan_to(w, m->target + fmin(by, left - MILLER_MARGIN), true);
	}
}

static void miller_destroy(struct c8ui_widget *w) {
	struct miller *m = w->data;
	c8ui_drag_finish(&m->drag);
	free(m->widths);
	free(m);
}

static void miller_narrow(struct c8ui_widget *w, bool narrow);

static const struct c8ui_widget_impl miller_impl = {
	.name = "miller",
	.measure = miller_measure,
	.layout = miller_layout,
	.draw = miller_draw,
	.draw_over = miller_draw_over,
	.event = miller_event,
	.tick = miller_tick,
	.destroy = miller_destroy,
	.reveal = miller_reveal,
	.clips = true,
	.narrow = miller_narrow,
};

struct c8ui_widget *c8ui_miller_new(void) {
	struct miller *m = calloc(1, sizeof(*m));
	m->drag.axis = C8UI_HORIZONTAL;
	m->edge = MILLER_EDGE;
	m->gap = MILLER_GAP;
	struct c8ui_widget *w = c8ui_widget_new(&miller_impl, m);
	w->fill = true;
	return w;
}

void c8ui_miller_set_spacing(struct c8ui_widget *w, double edge, double gap,
		double top, double bottom) {
	struct miller *m = w->data;
	m->edge = edge;
	m->gap = gap;
	m->top = top;
	m->bottom = bottom;
	c8ui_widget_queue_layout(w);
}

static void miller_narrow(struct c8ui_widget *w, bool narrow) {
	struct miller *m = w->data;
	if (m->narrow == narrow) {
		return;
	}
	m->narrow = narrow;
	c8ui_widget_queue_layout(w);
	if (!narrow) {
		show_column(w, m->count - 1);
	}
}

void c8ui_miller_set_base(struct c8ui_widget *w, int base) {
	((struct miller *)w->data)->base = base > 0 ? base : 0;
}

void c8ui_miller_on_change(struct c8ui_widget *w, c8ui_miller_fn fn,
		void *data) {
	struct miller *m = w->data;
	m->fn = fn;
	m->data = data;
}

int c8ui_miller_count(struct c8ui_widget *w) {
	return ((struct miller *)w->data)->count;
}

struct c8ui_widget *c8ui_miller_get(struct c8ui_widget *w, int i) {
	struct miller *m = w->data;
	return i >= 0 && i < m->count ? w->children[i] : NULL;
}

int c8ui_miller_index_of(struct c8ui_widget *w, struct c8ui_widget *inside) {
	for (struct c8ui_widget *c = inside; c; c = c->parent) {
		if (c->parent == w) {
			for (int i = 0; i < w->child_count; i++) {
				if (w->children[i] == c) {
					return i;
				}
			}
		}
	}
	return -1;
}

/* Takes away the columns from keep on, without telling */
static void trim(struct c8ui_widget *w, int keep) {
	struct miller *m = w->data;
	keep = keep < 0 ? 0 : keep;
	while (m->count > keep) {
		m->count--;
		c8ui_widget_destroy(w->children[m->count]);
	}
	c8ui_widget_queue_layout(w);
}

void c8ui_miller_close_after(struct c8ui_widget *w, int keep) {
	struct miller *m = w->data;
	if (keep >= m->count) {
		return;
	}
	trim(w, keep);
	if (m->fn) {
		m->fn(w, m->count, m->data);
	}
}

bool c8ui_miller_back(struct c8ui_widget *w) {
	struct miller *m = w->data;
	if (m->count <= m->base || m->count == 0) {
		return false;
	}
	c8ui_miller_close_after(w, m->count - 1);
	/* What was before it, back in sight (narrow: it shows anyway) */
	show_column(w, m->count - 1);
	if (m->narrow && m->count > 0) {
		c8ui_widget_enter(w->children[m->count - 1]);
	}
	return true;
}

int c8ui_miller_open(struct c8ui_widget *w, int after,
		struct c8ui_widget *content, double width) {
	struct miller *m = w->data;
	trim(w, after + 1);
	m->widths = realloc(m->widths, sizeof(double) * (m->count + 1));
	m->widths[m->count++] = width > 0 ? width : 400;
	c8ui_widget_add(w, content);
	c8ui_widget_queue_layout(w);
	int i = m->count - 1;
	if (i > 0 && w->root) {
		/* Metro's entrance, and the pan to it (only in a window: out of
		 * one it would never tick, and stay unseen) */
		c8ui_widget_enter(content);
		show_column(w, i);
	}
	if (m->fn) {
		m->fn(w, m->count, m->data);
	}
	return i;
}
