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

/* Read-only text with Pango markup (bold, italic, size, colour...), which
 * can flow from one container into the next, as XAML's RichTextBlock and
 * RichTextBlockOverflow do, or run in columns across a sideways scroll like
 * a magazine page.
 *
 * The text belongs to a chain: one Pango layout, wrapped at the width of the
 * first container. Each container shows the lines that fit its height, from
 * where the one before stopped.
 *
 * Links: Pango has no <a>, so set_markup takes each <a href="..."> out
 * (a span with an underline in its place) and keeps where its text is;
 * the rebuild colours those bytes in the accent, and a container whose
 * chain has a link fn takes clicks on them. */

#define DEFAULT_COLUMN_HEIGHT 480

struct rich;

struct rich_link {
	int start, end; // bytes of the layout's text
	char *uri;
};

struct chain {
	int refs;
	struct rich **members;
	int count, cap;

	char *markup;
	char *family; // NULL: the widget's font
	double size; // 0: body text
	uint32_t color;
	bool has_color, justify;
	double line_spacing; // 0: the font's

	PangoLayout *layout;
	double layout_width; // what it wraps at
	double natural; // how wide its widest line is
	bool dirty;
	double *tops, *bottoms;
	int lines;
	double avail; // what the first member was last offered

	struct rich_link *links;
	int nlinks;
	c8ui_rich_link_fn link_fn;
	void *link_data;

	/* Columns mode: one widget holding them all */
	bool columns;
	double col_width, col_gap;
	int ncols;
	int *col_first, *col_last;
	double col_height; // the height the columns were measured for
	double one_width; // narrow: one column this wide, all the text down
};

struct rich {
	struct chain *chain;
	struct c8ui_widget *w;
	int first, last; // lines shown
	int pressed_link; // -1: none
};

/* The chain */

static struct chain *chain_new(void) {
	struct chain *ch = calloc(1, sizeof(*ch));
	ch->refs = 1;
	ch->dirty = true;
	ch->markup = strdup("");
	return ch;
}

static void links_clear(struct chain *ch) {
	for (int i = 0; i < ch->nlinks; i++) {
		free(ch->links[i].uri);
	}
	free(ch->links);
	ch->links = NULL;
	ch->nlinks = 0;
}

static void chain_free(struct chain *ch) {
	if (--ch->refs > 0) {
		return;
	}
	links_clear(ch);
	if (ch->layout) {
		g_object_unref(ch->layout);
	}
	free(ch->members);
	free(ch->markup);
	free(ch->family);
	free(ch->tops);
	free(ch->bottoms);
	free(ch->col_first);
	free(ch->col_last);
	free(ch);
}

static void chain_insert(struct chain *ch, struct rich *r, int index) {
	if (ch->count == ch->cap) {
		ch->cap = ch->cap ? ch->cap * 2 : 4;
		ch->members = realloc(ch->members, sizeof(*ch->members) * ch->cap);
	}
	index = index < 0 || index > ch->count ? ch->count : index;
	memmove(ch->members + index + 1, ch->members + index,
		sizeof(*ch->members) * (ch->count - index));
	ch->members[index] = r;
	ch->count++;
	ch->refs++;
	r->chain = ch;
}

static void chain_remove(struct rich *r) {
	struct chain *ch = r->chain;
	for (int i = 0; i < ch->count; i++) {
		if (ch->members[i] == r) {
			memmove(ch->members + i, ch->members + i + 1,
				sizeof(*ch->members) * (ch->count - i - 1));
			ch->count--;
			break;
		}
	}
	/* The ones left show the text from the start again */
	for (int i = 0; i < ch->count; i++) {
		c8ui_widget_queue_layout(ch->members[i]->w);
	}
	chain_free(ch);
	r->chain = NULL;
}

/* How wide the text is wrapped */
static double chain_width(struct chain *ch) {
	if (ch->columns) {
		return ch->one_width > 0 ? ch->one_width : ch->col_width;
	}
	if (ch->count == 0) {
		return 1;
	}
	struct c8ui_widget *w0 = ch->members[0]->w;
	double width = w0->fixed_width > 0 ? w0->fixed_width :
		ch->avail > 0 ? ch->avail : w0->rect.width;
	return width < 1 ? 1 : width;
}

static void chain_rebuild(struct chain *ch, double width) {
	if (ch->layout) {
		g_object_unref(ch->layout);
		ch->layout = NULL;
	}
	if (ch->count == 0) {
		return;
	}
	struct c8ui_widget *w0 = ch->members[0]->w;
	struct c8ui_font font = c8ui_text_font(C8UI_TEXT_BODY);
	if (ch->size > 0) {
		font.size = ch->size;
	}
	const char *family = ch->family ? ch->family : c8ui_widget_font(w0);
	PangoLayout *layout = c8ui_text_layout(c8ui_measure_cr(), family, font, "",
		0, 0);
	pango_layout_set_width(layout, (int)(width * PANGO_SCALE));
	pango_layout_set_wrap(layout, PANGO_WRAP_WORD_CHAR);
	pango_layout_set_justify(layout, ch->justify);
	if (ch->line_spacing > 0) {
		pango_layout_set_line_spacing(layout, (float)ch->line_spacing);
	}
	if (pango_parse_markup(ch->markup, -1, 0, NULL, NULL, NULL, NULL)) {
		pango_layout_set_markup(layout, ch->markup, -1);
		if (ch->nlinks > 0) {
			PangoAttrList *attrs = pango_layout_get_attributes(layout);
			attrs = attrs ? pango_attr_list_copy(attrs) : pango_attr_list_new();
			uint32_t a = c8ui_widget_colors(w0).accent;
			for (int i = 0; i < ch->nlinks; i++) {
				PangoAttribute *fg = pango_attr_foreground_new(
					((a >> 16) & 0xff) * 257, ((a >> 8) & 0xff) * 257,
					(a & 0xff) * 257);
				fg->start_index = ch->links[i].start;
				fg->end_index = ch->links[i].end;
				pango_attr_list_change(attrs, fg);
			}
			pango_layout_set_attributes(layout, attrs);
			pango_attr_list_unref(attrs);
		}
	} else {
		/* Not markup: show it as it is (its links can't be found) */
		pango_layout_set_text(layout, ch->markup, -1);
		links_clear(ch);
	}
	ch->layout = layout;
	ch->layout_width = width;
	PangoRectangle ink, logical;
	pango_layout_get_pixel_extents(layout, &ink, &logical);
	ch->natural = logical.x + logical.width;

	int line_count = pango_layout_get_line_count(layout);
	ch->tops = realloc(ch->tops, sizeof(double) * (line_count + 1));
	ch->bottoms = realloc(ch->bottoms, sizeof(double) * (line_count + 1));
	ch->lines = 0;
	PangoLayoutIter *it = pango_layout_get_iter(layout);
	do {
		PangoRectangle r;
		pango_layout_iter_get_line_extents(it, NULL, &r);
		if (ch->lines < line_count) {
			ch->tops[ch->lines] = (double)r.y / PANGO_SCALE;
			ch->bottoms[ch->lines] = (double)(r.y + r.height) / PANGO_SCALE;
			ch->lines++;
		}
	} while (pango_layout_iter_next_line(it));
	pango_layout_iter_free(it);
}

/* Gives each container its lines; true if any changed */
static bool chain_flow(struct chain *ch) {
	bool changed = false;
	if (ch->columns) {
		double height = ch->count ? ch->col_height : 0;
		int line = 0, n = 0;
		int cap = 4;
		int *first = malloc(sizeof(int) * cap), *last = malloc(sizeof(int) * cap);
		while (line < ch->lines || n == 0) {
			if (n == cap) {
				cap *= 2;
				first = realloc(first, sizeof(int) * cap);
				last = realloc(last, sizeof(int) * cap);
			}
			first[n] = line;
			double top = line < ch->lines ? ch->tops[line] : 0;
			while (line < ch->lines && (line == first[n] ||
					ch->bottoms[line] - top <= height)) {
				line++;
			}
			last[n] = line;
			n++;
		}
		if (n != ch->ncols || memcmp(first, ch->col_first, sizeof(int) * n) ||
				memcmp(last, ch->col_last, sizeof(int) * n)) {
			changed = true;
		}
		free(ch->col_first);
		free(ch->col_last);
		ch->col_first = first;
		ch->col_last = last;
		ch->ncols = n;
		return changed;
	}
	int line = 0;
	for (int i = 0; i < ch->count; i++) {
		struct rich *r = ch->members[i];
		double cap = r->w->fixed_height > 0 ? r->w->fixed_height :
			i + 1 < ch->count && r->w->rect.height > 0 ? r->w->rect.height :
			1e9;
		int first = line;
		double top = line < ch->lines ? ch->tops[line] : 0;
		while (line < ch->lines && (line == first ||
				ch->bottoms[line] - top <= cap)) {
			line++;
		}
		if (r->first != first || r->last != line) {
			changed = true;
		}
		r->first = first;
		r->last = line;
	}
	return changed;
}

static void chain_update(struct chain *ch) {
	if (ch->count == 0) {
		return;
	}
	double width = chain_width(ch);
	if (ch->layout == NULL || ch->dirty || fabs(width - ch->layout_width) > 0.5) {
		ch->dirty = false;
		chain_rebuild(ch, width);
	}
	if (chain_flow(ch)) {
		for (int i = 0; i < ch->count; i++) {
			c8ui_widget_queue_layout(ch->members[i]->w);
		}
	}
}

static void chain_changed(struct chain *ch) {
	ch->dirty = true;
	for (int i = 0; i < ch->count; i++) {
		c8ui_widget_queue_layout(ch->members[i]->w);
	}
}

static double range_height(struct chain *ch, int first, int last) {
	if (last <= first || last > ch->lines) {
		return 0;
	}
	return ch->bottoms[last - 1] - ch->tops[first];
}

/* Draws lines first..last at x, y */
static void draw_range(struct c8ui_widget *w, struct chain *ch, cairo_t *cr,
		double x, double y, int first, int last) {
	if (ch->layout == NULL || last <= first) {
		return;
	}
	struct c8ui_colors c = c8ui_widget_colors(w);
	cairo_save(cr);
	cairo_rectangle(cr, x, y, ch->layout_width + 1, range_height(ch, first, last));
	cairo_clip(cr);
	cairo_translate(cr, x, y - ch->tops[first]);
	c8ui_set_source(cr, ch->has_color ? ch->color : c.fg,
		w->disabled ? 0.4 : 1);
	pango_cairo_update_layout(cr, ch->layout);
	pango_cairo_show_layout(cr, ch->layout);
	cairo_restore(cr);
}

/* A container */

static void rich_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct rich *r = w->data;
	struct chain *ch = r->chain;
	if (ch->count && ch->members[0] == r) {
		ch->avail = avail;
	}
	chain_update(ch);
	/* As wide as its text when that is less than the room (a short line
	 * in a grid's column); measured by the wrap width, every rich text
	 * took all the room it was offered */
	*width = ch->layout && ch->natural < avail ? ch->natural : avail;
	if (w->fixed_height > 0) {
		*height = w->fixed_height;
	} else {
		*height = range_height(ch, r->first, r->last);
	}
}

static void rich_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct rich *r = w->data;
	chain_update(r->chain);
	draw_range(w, r->chain, cr, w->rect.x, w->rect.y, r->first, r->last);
}

static void rich_destroy(struct c8ui_widget *w) {
	struct rich *r = w->data;
	if (r->chain) {
		chain_remove(r);
	}
	free(r);
}

/* The link under x, y (root coordinates), or -1 */
static int link_at(struct rich *r, double x, double y) {
	struct chain *ch = r->chain;
	if (ch == NULL || ch->layout == NULL || ch->nlinks == 0 ||
			r->last <= r->first || !c8ui_rect_contains(&r->w->rect, x, y)) {
		return -1;
	}
	double lx = x - r->w->rect.x;
	double ly = y - r->w->rect.y + ch->tops[r->first];
	if (ly > ch->bottoms[r->last - 1]) {
		return -1;
	}
	int index, trailing;
	/* False past either end of the line: not on its text */
	if (!pango_layout_xy_to_index(ch->layout, (int)(lx * PANGO_SCALE),
			(int)(ly * PANGO_SCALE), &index, &trailing)) {
		return -1;
	}
	for (int i = 0; i < ch->nlinks; i++) {
		if (index >= ch->links[i].start && index < ch->links[i].end) {
			return i;
		}
	}
	return -1;
}

static bool rich_event(struct c8ui_widget *w, const struct c8ui_event *ev) {
	struct rich *r = w->data;
	switch (ev->type) {
	case C8UI_EVENT_ENTER:
	case C8UI_EVENT_MOTION:
		c8ui_widget_set_cursor(w, link_at(r, ev->x, ev->y) >= 0 ?
			C8UI_CURSOR_POINTER : C8UI_CURSOR_DEFAULT);
		return false;
	case C8UI_EVENT_LEAVE:
		c8ui_widget_set_cursor(w, C8UI_CURSOR_DEFAULT);
		return false;
	case C8UI_EVENT_PRESS:
		if (ev->button != C8UI_BUTTON_LEFT) {
			return false;
		}
		r->pressed_link = link_at(r, ev->x, ev->y);
		return r->pressed_link >= 0;
	case C8UI_EVENT_RELEASE: {
		int i = r->pressed_link;
		r->pressed_link = -1;
		if (i < 0 || link_at(r, ev->x, ev->y) != i) {
			return i >= 0;
		}
		struct chain *ch = r->chain;
		/* A copy: the fn may well set new markup */
		char *uri = strdup(ch->links[i].uri);
		if (ch->link_fn) {
			ch->link_fn(w, uri, ch->link_data);
		}
		free(uri);
		return true;
	}
	default:
		return false;
	}
}

static const struct c8ui_widget_impl rich_impl = {
	.name = "rich-text",
	.measure = rich_measure,
	.draw = rich_draw,
	.destroy = rich_destroy,
};

/* The same taking clicks on links: only for a chain with a link fn, as a
 * widget that takes events is where the pointer hovers, and a rich text
 * without links mustn't take that from what holds it */
static const struct c8ui_widget_impl rich_link_impl = {
	.name = "rich-text",
	.measure = rich_measure,
	.draw = rich_draw,
	.event = rich_event,
	.destroy = rich_destroy,
};

static void chain_impls(struct chain *ch) {
	for (int i = 0; i < ch->count; i++) {
		ch->members[i]->w->impl = ch->link_fn ? &rich_link_impl : &rich_impl;
	}
}

static struct c8ui_widget *rich_make(struct chain *own) {
	struct rich *r = calloc(1, sizeof(*r));
	r->pressed_link = -1;
	struct c8ui_widget *w = c8ui_widget_new(&rich_impl, r);
	r->w = w;
	chain_insert(own, r, -1);
	chain_free(own); // chain_insert took the reference
	return w;
}

struct c8ui_widget *c8ui_rich_new(const char *markup) {
	struct chain *ch = chain_new();
	struct c8ui_widget *w = rich_make(ch);
	c8ui_rich_set_markup(w, markup);
	return w;
}

struct c8ui_widget *c8ui_rich_overflow_new(void) {
	return rich_make(chain_new());
}

void c8ui_rich_set_overflow(struct c8ui_widget *w,
		struct c8ui_widget *overflow) {
	struct rich *r = w->data, *o = overflow->data;
	struct chain *ch = r->chain;
	if (o->chain == ch || ch->columns) {
		return;
	}
	/* Leaves its own chain, the text of which it had none of */
	chain_remove(o);
	int at = 0;
	for (int i = 0; i < ch->count; i++) {
		if (ch->members[i] == r) {
			at = i + 1;
		}
	}
	chain_insert(ch, o, at);
	chain_impls(ch);
	chain_changed(ch);
}

/* What an entity (at s, its &) stands for into out (4 bytes or more);
 * returns how many bytes that is and sets *taken to the entity's length,
 * 0 when it isn't one */
static int entity(const char *s, char *out, int *taken) {
	static const struct { const char *name; char c; } named[] = {
		{ "&amp;", '&' }, { "&lt;", '<' }, { "&gt;", '>' },
		{ "&quot;", '"' }, { "&apos;", '\'' },
	};
	*taken = 0;
	for (size_t i = 0; i < sizeof(named) / sizeof(named[0]); i++) {
		size_t n = strlen(named[i].name);
		if (strncmp(s, named[i].name, n) == 0) {
			*taken = (int)n;
			out[0] = named[i].c;
			return 1;
		}
	}
	if (s[1] == '#') {
		char *end;
		bool hex = s[2] == 'x' || s[2] == 'X';
		unsigned long c = strtoul(s + (hex ? 3 : 2), &end, hex ? 16 : 10);
		if (*end == ';' && end > s + (hex ? 3 : 2)) {
			*taken = (int)(end - s) + 1;
			return g_unichar_to_utf8((gunichar)c, out);
		}
	}
	return 0;
}

/* An attribute's value, entities read, from a tag (p to q, the >) */
static char *tag_attr(const char *p, const char *q, const char *name) {
	size_t n = strlen(name);
	for (const char *a = p + 1; a + n < q; a++) { // p is the <
		if (strncmp(a, name, n) != 0 || !strchr(" \t\n", a[-1])) {
			continue;
		}
		const char *v = a + n;
		while (*v == ' ') {
			v++;
		}
		if (*v++ != '=') {
			continue;
		}
		while (*v == ' ') {
			v++;
		}
		char quote = *v;
		if (quote != '"' && quote != '\'') {
			continue;
		}
		GString *out = g_string_new(NULL);
		for (v++; v < q && *v != quote; v++) {
			char buf[8];
			int taken, len = *v == '&' ? entity(v, buf, &taken) : 0;
			if (len > 0) {
				g_string_append_len(out, buf, len);
				v += taken - 1;
			} else {
				g_string_append_c(out, *v);
			}
		}
		return g_string_free(out, FALSE);
	}
	return NULL;
}

/* The markup with its <a href> taken out into ch->links */
static char *take_links(struct chain *ch, const char *m) {
	links_clear(ch);
	GString *out = g_string_new(NULL);
	int text = 0, open = -1, cap = 0;
	const char *p = m;
	while (*p) {
		if (*p == '&') {
			char buf[8];
			int taken, len = entity(p, buf, &taken);
			if (taken > 0) {
				text += len;
				g_string_append_len(out, p, taken);
				p += taken;
				continue;
			}
		}
		if (*p != '<') {
			text++;
			g_string_append_c(out, *p++);
			continue;
		}
		/* A tag, to its > (one in quotes doesn't end it) */
		const char *q = p + 1;
		char quote = 0;
		while (*q && (quote || *q != '>')) {
			if (quote) {
				quote = *q == quote ? 0 : quote;
			} else if (*q == '"' || *q == '\'') {
				quote = *q;
			}
			q++;
		}
		if (*q == '\0') {
			g_string_append(out, p); // broken: Pango will say so
			break;
		}
		if (p[1] == 'a' && strchr(" \t\n>", p[2])) {
			if (open < 0) {
				if (ch->nlinks == cap) {
					cap = cap ? cap * 2 : 4;
					ch->links = realloc(ch->links, sizeof(*ch->links) * cap);
				}
				char *uri = tag_attr(p, q, "href");
				open = ch->nlinks++;
				ch->links[open] = (struct rich_link){ text, text,
					uri ? uri : strdup("") };
			}
			g_string_append(out, "<span underline=\"single\">");
		} else if (strncmp(p, "</a>", 4) == 0) {
			if (open >= 0) {
				ch->links[open].end = text;
				open = -1;
			}
			g_string_append(out, "</span>");
		} else {
			g_string_append_len(out, p, q - p + 1);
		}
		p = q + 1;
	}
	if (open >= 0) {
		ch->links[open].end = text;
	}
	return g_string_free(out, FALSE);
}

void c8ui_rich_set_markup(struct c8ui_widget *w, const char *markup) {
	struct chain *ch = ((struct rich *)w->data)->chain;
	free(ch->markup);
	ch->markup = take_links(ch, markup ? markup : "");
	chain_changed(ch);
}

void c8ui_rich_on_link(struct c8ui_widget *w, c8ui_rich_link_fn fn,
		void *data) {
	struct chain *ch = ((struct rich *)w->data)->chain;
	if (ch->columns) {
		return; // its widget isn't a rich text's to swap
	}
	ch->link_fn = fn;
	ch->link_data = data;
	chain_impls(ch);
}

void c8ui_rich_set_font(struct c8ui_widget *w, const char *family,
		double size) {
	struct chain *ch = ((struct rich *)w->data)->chain;
	free(ch->family);
	ch->family = c8ui_dup_or_null(family);
	ch->size = size;
	chain_changed(ch);
}

void c8ui_rich_set_color(struct c8ui_widget *w, uint32_t rgb) {
	struct chain *ch = ((struct rich *)w->data)->chain;
	ch->color = rgb;
	ch->has_color = true;
	c8ui_widget_queue_draw(w);
}

void c8ui_rich_set_justify(struct c8ui_widget *w, bool justify) {
	struct chain *ch = ((struct rich *)w->data)->chain;
	ch->justify = justify;
	chain_changed(ch);
}

void c8ui_rich_set_line_spacing(struct c8ui_widget *w, double factor) {
	struct chain *ch = ((struct rich *)w->data)->chain;
	ch->line_spacing = factor > 0 ? factor : 0;
	chain_changed(ch);
}

bool c8ui_rich_is_clipped(struct c8ui_widget *w) {
	struct rich *r = w->data;
	struct chain *ch = r->chain;
	chain_update(ch);
	return ch->count && ch->members[ch->count - 1] == r &&
		r->last < ch->lines;
}

/* Columns */

static void columns_measure(struct c8ui_widget *w, double avail, double *width,
		double *height) {
	struct rich *r = w->data;
	struct chain *ch = r->chain;
	if (w->narrow) {
		/* One column the width there is, as tall as the text */
		ch->one_width = avail > 1 && avail < 1e5 ? avail : ch->col_width;
		ch->col_height = 1e9;
		chain_update(ch);
		*width = ch->one_width;
		*height = range_height(ch, 0, ch->lines);
		return;
	}
	ch->one_width = 0;
	double h = w->fixed_height > 0 ? w->fixed_height :
		w->rect.height > 0 ? w->rect.height : DEFAULT_COLUMN_HEIGHT;
	ch->col_height = h;
	chain_update(ch);
	*width = ch->ncols * ch->col_width + (ch->ncols - 1) * ch->col_gap;
	if (*width > avail && avail < 1e5) {
		/* Never narrower than one column's worth, but not past what a
		 * parent that scrolls offers it either */
		*width = avail > ch->col_width ? avail : ch->col_width;
	}
	*height = h;
}

static void columns_layout(struct c8ui_widget *w) {
	struct rich *r = w->data;
	struct chain *ch = r->chain;
	/* The height it was given is not the one it was measured for */
	if (!w->narrow && fabs(w->rect.height - ch->col_height) > 0.5 && w->rect.height > 0) {
		ch->col_height = w->rect.height;
		chain_update(ch);
		c8ui_widget_queue_layout(w);
	}
}

static void columns_draw(struct c8ui_widget *w, cairo_t *cr) {
	struct rich *r = w->data;
	struct chain *ch = r->chain;
	chain_update(ch);
	for (int i = 0; i < ch->ncols; i++) {
		draw_range(w, ch, cr, w->rect.x + i * (ch->col_width + ch->col_gap),
			w->rect.y, ch->col_first[i], ch->col_last[i]);
	}
}

static void columns_narrow(struct c8ui_widget *w, bool narrow) {
	(void)narrow;
	c8ui_widget_queue_layout(w);
}

static const struct c8ui_widget_impl columns_impl = {
	.name = "rich-columns",
	.measure = columns_measure,
	.layout = columns_layout,
	.draw = columns_draw,
	.destroy = rich_destroy,
	.narrow = columns_narrow,
};

struct c8ui_widget *c8ui_rich_columns_new(const char *markup,
		double column_width, double gap) {
	struct chain *ch = chain_new();
	ch->columns = true;
	ch->col_width = column_width > 1 ? column_width : 320;
	ch->col_gap = gap >= 0 ? gap : 40;
	ch->col_height = DEFAULT_COLUMN_HEIGHT;
	struct rich *r = calloc(1, sizeof(*r));
	struct c8ui_widget *w = c8ui_widget_new(&columns_impl, r);
	r->w = w;
	chain_insert(ch, r, -1);
	chain_free(ch);
	c8ui_rich_set_markup(w, markup);
	return w;
}

int c8ui_rich_columns_count(struct c8ui_widget *w) {
	struct chain *ch = ((struct rich *)w->data)->chain;
	chain_update(ch);
	return ch->ncols;
}
