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

/* One line of editable text, for anything that draws a text box */

#define MASK_CHAR "●"
#define MASK_LEN (sizeof(MASK_CHAR) - 1)

struct paste {
	struct c8ui_textedit *te; // NULL once it's gone or a newer paste came
};

struct c8ui_textedit {
	GString *text;
	size_t cursor, anchor; // byte offsets; anchor != cursor: a selection
	bool password;
	GString *mask; // what a password shows: a dot per character
	struct paste *paste;
	c8ui_textedit_fn change_fn;
	void *change_data;
};

struct c8ui_textedit *c8ui_textedit_new(const char *text) {
	struct c8ui_textedit *te = calloc(1, sizeof(*te));
	te->text = g_string_new(text ? text : "");
	te->cursor = te->anchor = te->text->len;
	return te;
}

void c8ui_textedit_free(struct c8ui_textedit *te) {
	if (te == NULL) {
		return;
	}
	if (te->paste) {
		te->paste->te = NULL;
	}
	if (te->password) {
		explicit_bzero(te->text->str, te->text->allocated_len);
		g_string_free(te->mask, TRUE);
	}
	g_string_free(te->text, TRUE);
	free(te);
}

const char *c8ui_textedit_get(struct c8ui_textedit *te) {
	return te->text->str;
}

void c8ui_textedit_set(struct c8ui_textedit *te, const char *text) {
	g_string_assign(te->text, text ? text : "");
	te->cursor = te->anchor = te->text->len;
}

void c8ui_textedit_set_password(struct c8ui_textedit *te, bool password) {
	if (te->password == password) {
		return;
	}
	te->password = password;
	if (password) {
		te->mask = g_string_new(NULL);
	} else {
		g_string_free(te->mask, TRUE);
		te->mask = NULL;
	}
}

void c8ui_textedit_on_change(struct c8ui_textedit *te, c8ui_textedit_fn fn,
		void *data) {
	te->change_fn = fn;
	te->change_data = data;
}

bool c8ui_textedit_has_selection(struct c8ui_textedit *te) {
	return te->cursor != te->anchor;
}

void c8ui_textedit_select_all(struct c8ui_textedit *te) {
	te->anchor = 0;
	te->cursor = te->text->len;
}

void c8ui_textedit_deselect(struct c8ui_textedit *te) {
	te->anchor = te->cursor;
}

/* The text as drawn, and byte offsets into it and back */
static const char *shown(struct c8ui_textedit *te) {
	if (!te->password) {
		return te->text->str;
	}
	g_string_truncate(te->mask, 0);
	for (const char *p = te->text->str; *p; p = g_utf8_next_char(p)) {
		g_string_append(te->mask, MASK_CHAR);
	}
	return te->mask->str;
}

static int shown_index(struct c8ui_textedit *te, size_t i) {
	if (!te->password) {
		return (int)i;
	}
	return (int)(g_utf8_pointer_to_offset(te->text->str, te->text->str + i) *
		MASK_LEN);
}

static size_t text_index(struct c8ui_textedit *te, int i) {
	if (!te->password) {
		return (size_t)i;
	}
	return (size_t)(g_utf8_offset_to_pointer(te->text->str, i / MASK_LEN) -
		te->text->str);
}

static void delete_selection(struct c8ui_textedit *te) {
	size_t a = MIN(te->cursor, te->anchor), b = MAX(te->cursor, te->anchor);
	g_string_erase(te->text, a, b - a);
	te->cursor = te->anchor = a;
}

void c8ui_textedit_insert(struct c8ui_textedit *te, const char *text) {
	delete_selection(te);
	/* One line: line breaks in pasted text become spaces */
	char *clean = strdup(text);
	for (char *p = clean; *p; p++) {
		if (*p == '\n' || *p == '\r' || *p == '\t') {
			*p = ' ';
		}
	}
	g_string_insert(te->text, te->cursor, clean);
	te->cursor += strlen(clean);
	te->anchor = te->cursor;
	free(clean);
}

static void pasted(void *data, const char *text) {
	struct paste *p = data;
	struct c8ui_textedit *te = p->te;
	free(p);
	if (te == NULL) {
		return;
	}
	te->paste = NULL;
	if (text && text[0]) {
		c8ui_textedit_insert(te, text);
		if (te->change_fn) {
			te->change_fn(te, te->change_data);
		}
	}
}

static void request_paste(struct c8ui_textedit *te, struct c8ui_root *root) {
	if (root == NULL || root->impl->request_paste == NULL) {
		return;
	}
	if (te->paste) {
		te->paste->te = NULL;
	}
	te->paste = calloc(1, sizeof(*te->paste));
	te->paste->te = te;
	c8ui_root_request_paste(root, pasted, te->paste);
}

static size_t prev_char(const char *s, size_t i) {
	return i == 0 ? 0 : (size_t)(g_utf8_prev_char(s + i) - s);
}

static size_t next_char(const char *s, size_t len, size_t i) {
	return i >= len ? len : (size_t)(g_utf8_next_char(s + i) - s);
}

static size_t word_boundary(const char *s, size_t len, size_t i, int dir) {
	if (dir < 0) {
		while (i > 0 && s[prev_char(s, i)] == ' ') {
			i = prev_char(s, i);
		}
		while (i > 0 && s[prev_char(s, i)] != ' ') {
			i = prev_char(s, i);
		}
	} else {
		while (i < len && s[i] != ' ') {
			i = next_char(s, len, i);
		}
		while (i < len && s[i] == ' ') {
			i = next_char(s, len, i);
		}
	}
	return i;
}

enum c8ui_edit_result c8ui_textedit_key(struct c8ui_textedit *te,
		struct c8ui_root *root, const struct c8ui_event *ev) {
	const char *s = te->text->str;
	size_t len = te->text->len;
	bool shift = ev->mods & C8UI_MOD_SHIFT;
	bool ctrl = ev->mods & C8UI_MOD_CTRL;
	bool sel = te->cursor != te->anchor;
	size_t to = te->cursor;
	switch (ev->sym) {
	case XKB_KEY_Left:
		if (!shift && sel) {
			to = MIN(te->cursor, te->anchor);
		} else if (ctrl && te->password) {
			to = 0;
		} else {
			to = ctrl ? word_boundary(s, len, te->cursor, -1) :
				prev_char(s, te->cursor);
		}
		break;
	case XKB_KEY_Right:
		if (!shift && sel) {
			to = MAX(te->cursor, te->anchor);
		} else if (ctrl && te->password) {
			to = len;
		} else {
			to = ctrl ? word_boundary(s, len, te->cursor, 1) :
				next_char(s, len, te->cursor);
		}
		break;
	case XKB_KEY_Home:
		to = 0;
		break;
	case XKB_KEY_End:
		to = len;
		break;
	case XKB_KEY_BackSpace:
		if (!sel) {
			te->anchor = ctrl ? (te->password ? 0 :
				word_boundary(s, len, te->cursor, -1)) :
				prev_char(s, te->cursor);
		}
		delete_selection(te);
		return C8UI_EDIT_CHANGED;
	case XKB_KEY_Delete:
		if (!sel) {
			te->anchor = ctrl ? (te->password ? len :
				word_boundary(s, len, te->cursor, 1)) :
				next_char(s, len, te->cursor);
		}
		delete_selection(te);
		return C8UI_EDIT_CHANGED;
	case XKB_KEY_a:
	case XKB_KEY_A:
		if (!ctrl) {
			goto typed;
		}
		c8ui_textedit_select_all(te);
		return C8UI_EDIT_MOVED;
	case XKB_KEY_c:
	case XKB_KEY_C:
	case XKB_KEY_x:
	case XKB_KEY_X:
		if (!ctrl) {
			goto typed;
		}
		/* A password stays out of the clipboard */
		if (!sel || te->password) {
			return C8UI_EDIT_MOVED;
		}
		size_t a = MIN(te->cursor, te->anchor), b = MAX(te->cursor, te->anchor);
		char *copy = g_strndup(s + a, b - a);
		if (root) {
			c8ui_root_set_clipboard(root, copy);
		}
		g_free(copy);
		if (ev->sym == XKB_KEY_x || ev->sym == XKB_KEY_X) {
			delete_selection(te);
			return C8UI_EDIT_CHANGED;
		}
		return C8UI_EDIT_MOVED;
	case XKB_KEY_v:
	case XKB_KEY_V:
		if (!ctrl) {
			goto typed;
		}
		request_paste(te, root);
		return C8UI_EDIT_MOVED;
	default:
	typed:
		if (ev->text && !ctrl && !(ev->mods & (C8UI_MOD_ALT | C8UI_MOD_SUPER)) &&
				(unsigned char)ev->text[0] >= 0x20 && ev->text[0] != 0x7f) {
			c8ui_textedit_insert(te, ev->text);
			return C8UI_EDIT_CHANGED;
		}
		return C8UI_EDIT_IGNORED;
	}
	te->cursor = to;
	if (!shift) {
		te->anchor = to;
	}
	return C8UI_EDIT_MOVED;
}

static size_t index_at(struct c8ui_textedit *te, const char *family,
		struct c8ui_font font, double x) {
	return text_index(te, c8ui_text_index_at(family, font, shown(te), x));
}

void c8ui_textedit_press(struct c8ui_textedit *te, const char *family,
		struct c8ui_font font, double x, bool extend) {
	te->cursor = index_at(te, family, font, x);
	if (!extend) {
		te->anchor = te->cursor;
	}
}

void c8ui_textedit_drag(struct c8ui_textedit *te, const char *family,
		struct c8ui_font font, double x) {
	te->cursor = index_at(te, family, font, x);
}

void c8ui_textedit_scroll_to_caret(struct c8ui_textedit *te,
		const char *family, struct c8ui_font font, double inner,
		double *scroll) {
	const char *str = shown(te);
	double cx = c8ui_text_x_of(family, font, str, shown_index(te, te->cursor));
	if (cx - *scroll > inner) {
		*scroll = cx - inner;
	} else if (cx < *scroll) {
		*scroll = cx;
	}
	double tw, th;
	c8ui_text_size(family, font, str, 0, 0, &tw, &th);
	if (tw - *scroll < inner) {
		*scroll = tw > inner ? tw - inner : 0;
	}
}

void c8ui_textedit_draw(struct c8ui_textedit *te, cairo_t *cr,
		const char *family, struct c8ui_font font, double x, double y,
		double top, double height, uint32_t accent, bool selection,
		bool caret, double alpha) {
	const char *str = shown(te);
	double th = 0, tw;
	c8ui_text_size(family, font, "Ag", 0, 0, &tw, &th);
	cairo_set_source_rgba(cr, 0, 0, 0, alpha);
	c8ui_text_draw(cr, family, font, str, x, y, 0, 0);
	if (selection && te->cursor != te->anchor) {
		size_t a = MIN(te->cursor, te->anchor), b = MAX(te->cursor, te->anchor);
		double x0 = x + c8ui_text_x_of(family, font, str, shown_index(te, a));
		double x1 = x + c8ui_text_x_of(family, font, str, shown_index(te, b));
		cairo_save(cr);
		cairo_rectangle(cr, x0, top, x1 - x0, height);
		cairo_clip_preserve(cr);
		c8ui_set_source(cr, accent, 1);
		cairo_fill(cr);
		cairo_set_source_rgb(cr, 1, 1, 1);
		c8ui_text_draw(cr, family, font, str, x, y, 0, 0);
		cairo_restore(cr);
	}
	if (caret && te->cursor == te->anchor) {
		double cx = x + c8ui_text_x_of(family, font, str,
			shown_index(te, te->cursor));
		cairo_set_source_rgb(cr, 0, 0, 0);
		cairo_rectangle(cr, round(cx), top + 1, 1, height - 2);
		cairo_fill(cr);
	}
}
